SQL – How To Check If A String Contains Numbers

Use the PATINDEX function to check for an integer value continued in the string.

If PATINDEX returns a value greater than 0 then the string does contain an integer, you can use PATINDEX to determine the position of the integer within the string.

If PATINDEX is not greater than zero then the string does not contain an integer value.

DECLARE @string varchar(50)
SET @string = ‘this is a string with numb3rs in it’

IF PATINDEX(‘%[0-9]%’,@string) > 0 
      PRINT ‘YES, The string has contains the number ‘ +
                  substring(@string,PATINDEX(‘%[0-9]%’,@string),1) +
                  ‘ at position ‘ +
                  cast(PATINDEX(‘%[0-9]%’,@string) as char)
ELSE 
      PRINT ‘NO, The string does not have numbers’

SQL – Check If One String Contains Another String (CHARINDEX)

The CHARINDEX() function returns the location of a search string within another string.

For Example:

This code will return 11, which equates to the position of ‘sentance’ within the string ‘This is a sentance’.

select charindex(‘sentance’,’This is a sentance’)

This can be used to check if string A is contained in String B by using the following command:

select * from TABLE
where charindex(‘ROB’,NAME) != 0

The above command will return rows from the database where the field NAME contains the string ‘ROB’.

Convert A String To Proper Case In Java

Converting a string to proper case in Java.
e.g. convert “roBErT” to “Robert”.

Example code:

String forename = “roBErT”;
String forenameforenameInitial = “”;

forename = forename.toLowerCase();
forenameInitial = forename.substring(0, 1).toUpperCase();
forename = forenameInitial + forename.substring(1,forename.length());

System.out.println(forename);

The string vaiable forename now has a value of  “Robert”.

JAVA replace string within a string

The following code replaces an instance of a string within a string:

String testString = “This is a text string”
testString = testString.replace(“text string”, “sentance”);

testString will now print “This is a sentance”.

The replace() function is case sensative, and will only carry out the replace if the case matches both strings.