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) { //Crea una stringa String name = "w3codebox"; System.out.println(name + "中的字符有:"); //Loop through each element for(int i = 0; i<name.length(); i++) { //Accedi a ogni carattere char a = name.charAt(i); System.out.print(a + ", "); } } }
Risultato di output
I caratteri in w3codebox sono: n,h,o,o,o,
In the above example, we usedfor loopVisit 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) { //Crea una stringa String name = "w3codebox"; System.out.println(name + "中的字符有:"); //Usa il ciclo for-each per esplorare ogni elemento for(char c : name.toCharArray()) { //Accedi a ogni carattere System.out.print(c + ", "); } } }
Risultato di output
I caratteri in w3codebox sono: n,h,o,o,o,
Nell'esempio sopra, abbiamo utilizzato toCharArray() per convertire la stringa in un array di char. Poi, abbiamo utilizzato Ciclo for-each Accedi a ogni elemento dell'array char.