loop string java code example

Example 1: java iterate over a string

String scientistName = "Isaac Newton";
 
for (int i = 0; i < scientistName.length(); i++) {
    System.out.print(scientistName.charAt(i) + " "); // I s a a c   N e w t o n
}

//*********************************************************
// you can cast a string into a char[]
String str = "strings are not primitive types!";
 

for (char ch : str.toCharArray()) {
    	System.out.print(scientistName.charAt(i) + " ");
    }
}

Example 2: iterate over string java

String str = "hello";
for (char c : str.toCharArray())
  //process c

Example 3: java loop through string

String s = "...stuff...";

for (int i = 0; i < s.length(); i++){
    char c = s.charAt(i);        
    //Process char
}

Example 4: loop through string in java

String s = "...stuff...";

for (int i = 0; i < s.length(); i++){
    char c = s.charAt(i);        
    //Process char
}

Example 5: loop and save letters in a string java

StringBuilder phone = new StringBuilder();
for (int i = 0; i < number.length(); i++){
    if (Character.isLetter(number.charAt(i))){
        phone.append(getNumber(Character.toUpperCase(number.charAt(i))));
    }else{
        phone.append(number.charAt(i));
    }
}

System.out.println("Your number is " + phone.toString());

Example 6: loop and save letters in a string java

public static void main(String[] args){
        Scanner input = new Scanner(System.in);

            System.out.print("Enter phone number: ");
            String number = input.nextLine();
            String phone ="";

            for (int i = 0; i < number.length(); i++){
                if (Character.isLetter(number.charAt(i)))
                    phone = getNumber(Character.toUpperCase(number.charAt(i)));
                else
                    number.charAt(i);
            }
            System.out.println("Your number is " + phone);              
    }


public static int getNumber(char uppercaseLetter){
        if (uppercaseLetter >= 'W' && uppercaseLetter <= 'Z')
            return 9;
        else if (uppercaseLetter >= 'T' && uppercaseLetter < 'W')
            return 8;
        else if (uppercaseLetter >= 'P' && uppercaseLetter < 'T')
            return 7;
        else if (uppercaseLetter >= 'M' && uppercaseLetter < 'P')
            return 6;
        else if (uppercaseLetter >= 'J' && uppercaseLetter < 'M')
            return 5;
        else if (uppercaseLetter >= 'G' && uppercaseLetter < 'J')
            return 4;
        else if (uppercaseLetter >= 'D' && uppercaseLetter < 'G')
            return 3;
        else 
            return 2;
    }
}