Finding all uppercase letters of a string in java

前端 未结 10 1059
后悔当初
后悔当初 2021-01-12 14:28

So I\'m trying to find all the uppercase letters in a string put in by the user but I keep getting this runtime error:

Exception in thread \"main\" java.lan         


        
10条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-12 15:06

    The array index out of bounds is due to the for loop not terminating on length - 1, it is terminating on length Most iterating for loops should be in the form:

    for (int i = 0; i < array.length; i++) {
        // access array[i];
    }
    

    It's the same with a string.

    Perhaps a cleaner way would be:

    String inputString; // get user input
    
    String outputString = "";
    
    for (int i = 0; i < inputString.length; i++) {
        c = inputString.charAt(i);
        outputString += Character.isUpperCase(c) ? c + " " : ""; 
    }
    System.out.println(outputString);
    

    Edit: Forgot String Doesn't implement Iterable, silly Java.

提交回复
热议问题