Strings and arrays
In some sense, a string looks like an array of characters.
It's possible to convert between strings and character arrays using special methods:
char[] chars = { 'A', 'B', 'C', 'D', 'E', 'F' };
String stringFromChars = String.valueOf(chars); // "ABCDEF"
char[] charsFromString = stringFromChars.toCharArray(); // { 'A', 'B', 'C', 'D', 'E', 'F' }
String theSameString = new String(stringFromChars); // "ABCDEF"
A string can be separated by delimiters to an array of strings. To perform this, call the method
split
passing a string for splitting.String text = "a long text";
String[] parts = text.split(" "); // [a, long, text]
Iterating over a string
It's possible to iterate over characters of a string using a loop (while, do-while, for-loop).
See the following example.
String scientistName = "Isaac Newton";
for (int i = 0; i < scientistName.length(); i++) {
System.out.print(scientistName.charAt(i) + " "); // print the current character
}
The code outputs:
I s a a c N e w t o n
If you'd like to use the for-each loop, first you should convert a string to an array of characters and iterate it.
String str = "strings are not primitive types!";
int count = 0;
for (char ch : str.toCharArray()) {
if (Character.isWhitespace(ch)) {
count++;
}
}
System.out.println(count); // 4
The code above counts and prints the number of spaces in
str
. The result is 4.