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’
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’.
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”.
Replaces each substring of this string that matches the given regular expression with the given replacement.
String s = “This is a string”;
s = s.replaceAll(” “,”");
s now equals “Thisisastring”
All white spaces have been replaced with the empty 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.