Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding all uppercase letters of a string in java

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.

like image 285
EvanD Avatar asked Oct 31 '12 03:10

EvanD


People also ask

How do you check if all letters in a string are uppercase?

To check if a string is in uppercase, we can use the isupper() method. isupper() checks whether every case-based character in a string is in uppercase, and returns a True or False value depending on the outcome.

How do you check if a string is all uppercase Java?

isUpperCase(char ch) determines if the specified character is an uppercase character. A character is uppercase if its general category type, provided by Character.

How do you print all uppercase letters in Java?

Java String toUpperCase() Method The toUpperCase() method converts a string to upper case letters. Note: The toLowerCase() method converts a string to lower case letters.

How do you find capital letters in Java?

To check whether a character is in Uppercase or not in Java, use the Character. isUpperCase() method.


1 Answers

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(Character::isUpperCase)
        .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
like image 88
ltlBeBoy Avatar answered Sep 20 '22 17:09

ltlBeBoy