Πρόγραμμα Java για επανάληψη μέσω κάθε χαρακτήρα της συμβολοσειράς.

Σε αυτό το σεμινάριο, θα μάθουμε να επαναλαμβάνουμε κάθε χαρακτήρα της συμβολοσειράς.

Για να κατανοήσετε αυτό το παράδειγμα, θα πρέπει να γνωρίζετε τις ακόλουθες εφαρμογές προγραμματισμού Java:

  • Συμβολοσειρά Java
  • Java για βρόχο
  • Java για κάθε βρόχο

Παράδειγμα 1: Περιηγηθείτε σε κάθε χαρακτήρα μιας συμβολοσειράς χρησιμοποιώντας το loop

 class Main ( public static void main(String() args) ( // create a string String name = "Programiz"; System.out.println("Characters in " + name + " are:"); // loop through each element for(int i = 0; i 

Output

 Characters in Programiz are: P, r, o, g, r, a, m, i, z,

In the above example, we have used the for-loop to access each element of the string. Here, we have used the charAt() method to access each character of the string.

Example 2: Loop through each character of a string using for-each loop

 class Main ( public static void main(String() args) ( // create a string String name = "Programiz"; System.out.println("Characters in string "" + name + " ":"); // loop through each element using for-each loop for(char c : name.toCharArray()) ( // access each character System.out.print(c + ", "); ) ) )

Output

 Characters in string "Programiz": P, r, o, g, r, a, m, i, z,

In the above example, we have converted the string into a char array using the toCharArray(). We then access each element of the char array using the for-each loop.

ενδιαφέροντα άρθρα...