English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

教程基础Java

Java flow control

Java array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Gestione delle eccezioni Java

Java List

Java Queue (queue)

Java Map collection

Java Set collection

Java Input/Output (I/O)

Java Reader/Writer

Other Java topics

Java program iterates over each character in the string

Completo di esempi Java

In this tutorial, we will learn to traverse each character of the string.

To understand this example, you should understand the followingJava programmingTopic:

Example 1: Use for loop to traverse each character of the string

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.

Esempio 2: Usare il ciclo for-each per esplorare ogni carattere della stringa

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.

Completo di esempi Java