Strings are an important data structure used in many common languages. Strings are stored as a sequence of characters. Strings can be used to represent text, as well as other objects, such as 2D maps. This recipe will describe how to use Strings.
A String variable can be initialized in a number of ways:
String s = "Hello World";
Dim s As String = "Hello " & "World"
A common operation is to extract the contents of a String. We can extract either a particular character or a whole substring, which will also have type String:
//print the second character of s
//extract contents between first and last 'l's in s
String res=s.substring(s.indexOf('l')+1, s.lastIndexOf('l'));
System.out.println(res); //prints "lo Wor"
'print the first 5 characters of s
Print Left$(s,5) 'prints "Hello"
'print 3 characters of s starting with the fifth character
Print Mid$(s,5,3) 'prints "o W"
Strings in Java are immutable, meaning that we cannot modify their contents directly. Instead, we can use a StringBuffer object, which can be modified character-by-character. Visual Basic does not suffer from this problem:
'replace the last 5 characters of s with “Earth”
Right$(s,5) = "Earth"
Print s 'prints "Hello Earth"
Often we need to check whether a String contains a particular substring. In the following we check whether s contains "el":
System.out.println(s+" contains el");
If InStr(s, "el") >= 1 Then
Print s & " contains el"
We can compare two Strings based on their lexicographical (dictionary) order. This is useful when we want to sort Strings:
//r = 0 if the Strings are identical (case-sensitive)
//r < 0 if string1 is lexicographically less than string2
//r > 0 if string1 is lexicographically greater than string2
result = StrComp(string1,string2,vbTextCompare)
Regular expressions are a very powerful tool. They can be used to search for predefined patterns in Strings, amongst other things (LINK to the article on Regular Expressions by Dan[Popovici] and mariusmuja). Lets check whether the String matches a regular expression of the form [0 or more numbers] [0 or more characters] [0 or more numbers]:
System.out.println("String has the form numbers-characters-numbers");
If "123abcd45" Like "[0-9]*[a-zA-Z]*[0-9]*" Then
Print "String has the form numbers-characters-numbers"
Strings can also be parsed as regular expressions. Here we will parse the String into words, ie., text separated by space:
String words=s.split(" ");
for (int i=words.length-1; i>=0; i--)
System.out.println(words[i]+" "); //prints "World Hello "
Dim word As String=s.Split(" ")(1)
Print word 'prints the second word "World"
Strings can also be used to simplify methods on integers. We will now obtain the most significant digit of an integer by converting it to a String:
System.out.println("The first digit of "+i+" is "+digit);
Lets compute the number of digits in an integer:
System.out.println("Number of digits in "+i+" is "+digits);