-2

I'm writing a program in Java. They say to not use String functions - so how can I get characters in a String using the index but not using charAt()?

other question has answer but they all are using charAt()

I also want to get characters one by one using a loop.

2 Answers2

2

There is a way not to use any String methods with java.text.CharacterIterator but you are not using indexes as well. I am not sure if this complies with your question.

CharacterIterator it = new StringCharacterIterator(yourString);
for(char c = it.first(); c != CharacterIterator.DONE; c = it.next()) {
  // do whatever you want with c
}
kyriakosSt
  • 1,754
  • 2
  • 15
  • 33
1

Use StringBuilder like this.

StringBuilder sb = new StringBuilder(yourString);
for (int i = 0; i < sb.length(); ++i)
    System.out.println(sb.charAt(i));