English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this tutorial, we will learn to traverse each character of the string.
To understand this example, you should understand the followingJava programmingTopic:
class Main { public static void main(String[] args) { //Create a string String name = "w3codebox"; System.out.println( name + "The characters in "); //Loop through each element for(int i = 0; i<name.length(); i++) { //Access each character char a = name.charAt(i); System.out.print(a + "', "); } } }
Output Result
w3The characters in codebox are: n,h,o,o,o,
In the above example, we usedfor loopto access each element of the string. Here, we use the charAt() method to access each character of the string.
class Main { public static void main(String[] args) { //Create a string String name = "w3codebox"; System.out.println( name + "The characters in "); //Use for-each loop traverses each element for(char c : name.toCharArray()) { //Access each character System.out.print(c + "', "); } } }
Output Result
w3The characters in codebox are: n,h,o,o,o,
In the above example, we use toCharArray() to convert the string to a char array. Then, we use for-each loop Access each element of the char array.