17

How can I iterate through a string in Java?

I'm trying to use a foreach style for loop

for (char x : examplestring) {
    //action
}
Jared Burrows
  • 54,294
  • 25
  • 151
  • 185
muttley91
  • 12,278
  • 33
  • 106
  • 160

4 Answers4

46

If you want to use enhanced loop, you can convert the string to charArray

for (char ch : exampleString.toCharArray()) {
  System.out.println(ch);
}
Jared Burrows
  • 54,294
  • 25
  • 151
  • 185
surajz
  • 3,471
  • 3
  • 32
  • 38
  • 8
    This is a lot worse that my version as it copies the `String` to a temporary array that is returned by the function. – cletus Sep 26 '10 at 18:25
  • @cletus - you can't access original array - String is immutable so same should be the source array. But in Java you can always modify an array, which would cause to break Java optimizations (internig). Anyway one copy is faster than many `length()` and `charAt()`. – gertas Sep 26 '10 at 18:43
  • 4
    @gertas that's exactly what I was saying. Because arrays are mutable it must be defensively copied. So you have the cost of that copy for what? Syntactic sugar. That's why this is a bad idea. – cletus Sep 26 '10 at 18:48
  • @cletus: but here it isn't syntactic sugar. Generally we have rather memory vs cpu problem. I wouldn't mind if JVM optimizes access to String methods somehow, but still you call `.lenght()` and `.charAt()` for each char. – gertas Sep 26 '10 at 18:56
  • @gertas: You need to give more credit to Java's optimizing compiler. Iterating by index is 2% faster on my machine (jre7-32bit-single) than iterating through a `char[]` copy. – Gunslinger47 Sep 26 '10 at 19:54
  • Like most things in java it won't be the CPU hit that kills you, it'll be all the garbage (temporary objects) you create. ‘length()‘ and ‘charAt()‘ are simple wrappers as well. If I found this code in a review I'd get it fixed. – cletus Sep 27 '10 at 01:16
  • @cletus: [Escape analysis](http://java.dzone.com/articles/escape-analysis-java-6-update) should lessen that burden. – Gunslinger47 Sep 27 '10 at 06:48
34

Java Strings aren't character Iterable. You'll need:

for (int i = 0; i < examplestring.length(); i++) {
  char c = examplestring.charAt(i);
  ...
}

Awkward I know.

Jared Burrows
  • 54,294
  • 25
  • 151
  • 185
cletus
  • 616,129
  • 168
  • 910
  • 942
2

Using Guava (r07) you can do this:

for(char c : Lists.charactersOf(someString)) { ... }

This has the convenience of using foreach while not copying the string to a new array. Lists.charactersOf returns a view of the string as a List.

ColinD
  • 108,630
  • 30
  • 201
  • 202
  • +1. I didn't know that r07 was out. Though, interestingly, this is the slowest of the available options. It took 49% longer to complete than an equivillant `charAt` test. – Gunslinger47 Sep 26 '10 at 20:26
  • @Gunslinger47: I imagine the need to box and unbox each char for this would slow it down a bit. The method is probably more intended to adapt strings for use with various `Collection`-based APIs than just for iteration like this. – ColinD Sep 27 '10 at 00:47
0

How about this

for (int i = 0; i < str.length(); i++) { 
    System.out.println(str.substring(i, i + 1)); 
} 
Jared Burrows
  • 54,294
  • 25
  • 151
  • 185
Dead Programmer
  • 12,427
  • 23
  • 80
  • 112