Finding all uppercase letters of a string in java

2019-02-17 15:41发布

问题:

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.lang.StringIndexOutOfBoundsException: 
String index out of range: 4
at java.lang.String.charAt(String.java:686)
at P43.main(P43.java:13)

I feel foolish but I just can't figure this out and oracle even talks about charAt on the page about java.lang.StringIndexOutOfBoundsException

Here is my code for finding the uppercase letters and printing them:

import java.io.*;
import java.util.*;

public class P43{
   public static void main(String[] args){
      Scanner in = new Scanner(System.in);
      //Uppercase
      String isUp = "";
      System.out.print("Please give a string: ");
      String x = in.next();
      int z = x.length();
      for(int y = 0; y <= z; y++){
         if(Character.isUpperCase(x.charAt(y))){
            char w = x.charAt(y);
            isUp = isUp + w + " ";
         }
      }
      System.out.println("The uppercase characters are " + isUp);
      //Uppercase
   }
}

I'd really appreciate any input and or help.

回答1:

for(int y = 0; y <= z; y++){

should be

for(int y = 0; y < z; y++){

Remember array index starts from ZERO.

String length returns

the number of 16-bit Unicode characters in the string

Because loop started from ZERO, loop should terminate at length-1.



回答2:

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<Character>, silly Java.



回答3:

With Java 8 you can also use lambdas. Convert the String into a IntStream, use a filter to get the uppercase characters only and create a new String by appending the filtered characters to a StringBuilder:

Scanner in = new Scanner(System.in);
System.out.print("Please give a string: ");
//Uppercase
String isUp = in.next()
        .chars()
        .filter((c) -> Character.isUpperCase(c))
        .collect(StringBuilder::new, // supplier
                StringBuilder::appendCodePoint, // accumulator
                StringBuilder::append) // combiner
        .toString();
System.out.println("The uppercase characters are " + isUp);
//Uppercase

Inspired by:

  • Adam Bien - Streaming A String
  • Simplest way to print anIntStream as a String


回答4:

Try this...

Method:

public int findUpperChar(String valitateStr) {
    for (int i = valitateStr.length() - 1; i >= 0; i--) {
        if (Character.isUpperCase(valitateStr.charAt(i))) {
            return i;
        }
    }
    return -1;
}

Usage:

String passwordStr = password.getText().toString();

 .......

int len = findUpperChar(passwordStr);

if ( len != -1) {

      capitals exist.   

  } else {

      no capitals exist.            
}


回答5:

Hi one of the easy step to find uppercase char in a given string...

Program

import java.io.*;
public class testUpper 
{
    public static void main(String args[]) throws IOException
    {
        String data,answer="";
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter any String : ");
        data=br.readLine();
        char[] findupper=data.toCharArray();
        for(int i=0;i<findupper.length;i++)
        {
            if(findupper[i]>=65&&findupper[i]<=91) //ascii value in between 65 and 91 is A to Z
            {
                answer+=findupper[i]; //adding only uppercase
            }
        }
        System.out.println("Answer : "+answer);
    }
}

Output

Enter any String :

Welcome to THe String WoRlD

Answer : WTHSWRD



回答6:

You can increase the readability of your code and benefit from some other features of modern Java here. Please use the Stream approach for solving this problem. Also, I suggest importing the least number of libraries into your class. Please avoid using .* while importing.

import java.util.Scanner;

public class P43 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Please give a string: ");
        String x = in.next();
        x.chars().filter(c -> Character.isUpperCase(c))
                .forEach(c -> System.out.print((char) c + " "));
    }
}

Sample input:

saveChangesInTheEditor

Sample output:

C I T E



回答7:

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.println("Enter the number");
    String str= input.nextLine();

    int ascii;
    for(int i=0; i<str.length(); i++) {
        ascii = str.charAt(i);
        System.out.println(ascii);
        if (ascii >= 65 && ascii <= 90) {
            System.out.println("captal letter found ::: "+ascii);
        }
    }
}


回答8:

public class Cama {

public static void main(String[] args) {
    String camal = "getStudentByName";
    String temp = "";
    for (int i = 0; i < camal.length(); i++) {
        if (Character.isUpperCase(camal.charAt(i))) {
            System.out.print(" " + Character.toLowerCase(camal.charAt(i)));
        } else if (i == 0) {
            System.out.print(Character.toUpperCase(camal.charAt(i)));
        }else{
            System.out.print(camal.charAt(i));
        }
    }
}
}