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 } 
0

4 Answers 4

51

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

for (char ch : exampleString.toCharArray()) { System.out.println(ch); } 
Sign up to request clarification or add additional context in comments.

8 Comments

This is a lot worse that my version as it copies the String to a temporary array that is returned by the function.
@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 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: 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: 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.
|
33

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.

Comments

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.

2 Comments

+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: 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.
0

How about this

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.