views:

147

answers:

4

How can I iterate through a string in Java?

I'm trying to use a foreach style for loop

for(char x : examplestring)
{
    //action
}
+7  A: 

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

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

Awkward I know.

cletus
Alright thanks, yeah I thought it'd be easier.
rar
+7  A: 

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

    for (char ch : exampleString.toCharArray()){
        System.out.println(ch);
    }
surajz
This is a lot worse that my version as it copies the `String` to a temporary array that is returned by the function.
cletus
@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
@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
@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
@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
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
@cletus: [Escape analysis](http://java.dzone.com/articles/escape-analysis-java-6-update) should lessen that burden.
Gunslinger47
+1  A: 

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
+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
@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
A: 

How about this

for (int i=0;i < str.length;i++) 
{ 
    System.out.println(str.substring(i,i)); 
} 
Suresh S