What is the easiest/best/most correct way to iterate through the characters of a string in Java?

前端 未结 15 1502
挽巷
挽巷 2020-11-22 11:14

StringTokenizer? Convert the String to a char[] and iterate over that? Something else?

15条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-22 11:42

    So typically there are two ways to iterate through string in java which has already been answered by multiple people here in this thread, just adding my version of it First is using

    String s = sc.next() // assuming scanner class is defined above
    for(int i=0; i

    If performance is at stake then I will recommend to use the first one in constant time, if it is not then going with the second one makes your work easier considering the immutability with string classes in java.

提交回复
热议问题