stackoverflow
stackoverflow

Reputation: 19444

How to make String class iterable? Possible?

How can I make this work in java?

String p = "Hello";

for(char i: p)
    System.out.print(i);

Upvotes: 2

Views: 1704

Answers (4)

mohamed omer
mohamed omer

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

Kumar Vivek Mitra
Kumar Vivek Mitra

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

arshajii
arshajii

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

Reimeus
Reimeus

Reputation: 159754

You could do:

for (char i: p.toCharArray())
    System.out.print(i);

Upvotes: 7

Related Questions