Java iterate through string

There are various methods to iterate through a string in java character by character. This article will explore many of those with example code.

Method 1: Using toCharArray()
String class has a toCharArray() method which returns array of all the characters of the string.
This array can be iterated using enhanced for loop as shown below.
Loop variable in each iteration is the current string character.

String s  = "codippa";
char[] charArray = s.toCharArray();
for (char c : charArray) {
  System.out.print(c);
}

Method 2: Using length() and charAt()
String class has a length() method which returns the number of characters in it. So, iterating from 0 to the number of characters, we can get each character using string’s charAt() method.
charAt() accepts an integer argument and returns the character at that index. Example,

String s  = "codippa";
for (int i = 0; i < s.length(); i++) {
  System.out.print(s.charAt(i));
}

Method 3: Using StringTokenizer
java.util.StringTokenizer divides a string into tokens based on a delimiter. Default delimiters are empty space, single space, tab and newline characters.
To get tokens, its nextToken() method is used and to check if there are more tokens, use its hasMoreTokens() method.

So, if a string without spaces is supplied to StringTokenizer, it will break it into tokens where each token is a character and it can be easily iterated over character by character. Example,

String s = "codippa";
StringTokenizer tokenizer = new StringTokenizer(s);
while(tokenizer.hasMoreTokens()) {
   System.out.println(tokenizer.nextToken());
}

Method 4: Using String.chars()
This method uses java 8 streams to iterate over characters of a string.
chars() method returns a stream of integers which can be iterated and each integer can be converted to its corresponding character format.

There are multiple ways to get the character for an integer such as direct casting, mapToObj() method etc., shown in the examples below
To iterate over a stream, use java 8 forEach() method.

String s = "codippa";

// cast int to char
s.chars().
   forEach(c -> System.out.print((char)c));

// convert int to char with Character class
s.chars().
   forEach(c -> System.out.print(Character.toChars(c)));

// map int to char with cast
s.chars().
   mapToObj(c -> (char)c).
   forEach(System.out::print);

// map int to char with Character class
s.chars().
   mapToObj(i -> Character.toChars(i)).
   forEach(System.out::print);

// map int to char with Character class
s.chars().
   mapToObj(Character::toChars).
   forEach(System.out::print);

All the methods above iterate through the characters of a string.

chars() method was intoduced in java 9.
It returns a stream of integers and you need to use a forEach() loop to iterate over it. Using mapToObj() is optional as evident from above examples.
Both mapToObj() and forEach() accept an argument of Functional interface type and hence, can be supplied with a Lambda expression.
Method 5: Using String.codePoints()
codePoints() method also returns a stream of integers for characters of a string and can be iterated using forEach() method similar to chars() in the previous section. Example,

String s = "codippa";

// cast int to char
s.codePoints().
   forEach(c -> System.out.print((char)c));

// convert int to char with Character class
s.codePoints().
   forEach(c -> System.out.print(Character.toChars(c)));

// map int to char with cast
s.codePoints().
   mapToObj(c -> (char)c).
   forEach(System.out::print);

// map int to char with Character class
s.codePoints().
   mapToObj(i -> Character.toChars(i)).
   forEach(System.out::print);

// map int to char with Character class
s.codePoints().
   mapToObj(Character::toChars).
   forEach(System.out::print);

codePoint() was also added in java 9.

Method 5: Using String.split()
split() method accepts a string argument and divides the string on which it is called, into parts, considering the argument string as a delimiter or a regular expression.
It returns an array whose elements are the strings returned after split. Thus, "iterateoverstring".split("over") will return an array with elements “iterate” and “string”.
Note that argument string does not occur in the result array.

If the argument string or regular expression does not occur in the string, then the returned array contains the original string as the single element.
So, if we split a string over empty string, then it will return an array containing the original string.
This string can be converted to a character array with toCharArray() and iterated using a for loop as shown earlier. Example,

String s = "codippa";
// split on empty string
String[] arr = s.split("");
// string array has only 1 string
char[] chars = arr[0].toCharArray();
// iterate through characters
for(char c: chars) {
   System.out.print(c)			
}

Method 6: Using StringCharacterIterator
java.text.StringCharacterIterator class can be used to iterate over a string using its next() and current() methods.

next() method moves the position of iterator to the next character, current() returns the character at current iterator position. To check the end of the string, use StringCharacterIterator.DONE constant. Example,

String s = "codippa";
StringCharacterIterator itr = new StringCharacterIterator(s);
for (char c = itr.current(); c != StringCharacterIterator.DONE; c = itr.next()) {
  System.out.print(c);
}

Method 7: Using Guava Library
com.google.common.collect.Lists class from Guava library has a charactersOf() method which accepts a string argument and returns a list of characters in it.
This list can be iterated using forEach() loop or enhanced for loop. Example,

String s = "codippa";
java.util.List<Character> characters = Lists.charactersOf(s);
characters.forEach(c->System.out.print(c));

charactersOf() is a static method and so, it can be invoked directly with class name.

Add Guava library to your project using the following Maven or Gradle dependencies

// Maven
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>30.1.1-jre</version>
</dependency>


// Gradle
implementation group: 'com.google.guava', name: 'guava', version: '30.1.1-jre'

That is all on different methods to iterate through characters of a string in java. Hope the article was useful.

0

Liked the article ? Spread the word...