Reputation: 19444
How can I make this work in java?
String p = "Hello";
for(char i: p)
System.out.print(i);
Upvotes: 2
Views: 1704
Reputation: 11
I totally misunderstood the question at first. If you just want to iterate over the String , use the charArray method as others answered. But if you also want to remove characters and append , then use a StringBuilder.
Upvotes: 1
Reputation: 33534
- What you mean by make the String
iterable, its only possible by converting it into char
array.
- If you want to access characters within the String
directly you can use chatAt()
method.
- But if you want to make it iterable
then go for toCharArray()
method
Eg:
char[] arr = p.toCharArray();
for (char i: arr){
System.out.print(i);
}
Upvotes: 0
Reputation: 129507
Strings are not Iterable
in Java (as opposed to in Python, for instance), but you can loop over their internal character arrays:
for (char i : p.toCharArray())
System.out.print(i);
Upvotes: 5
Reputation: 159754
You could do:
for (char i: p.toCharArray())
System.out.print(i);
Upvotes: 7