0

i wanted to get the uppercase characters in the string and also there count

package TEST;

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class case_test {
    public static void main(String agrs[]) {

        String str1 = "", regx;
        regx = "[A-Z]+";
        Scanner sc = new Scanner(System.in);
        Pattern pattern = Pattern.compile(regx);
        Matcher matcher = pattern.matcher(str1);
        int count = 0;

        System.out.println("ENTER A SENTENCE");
        str1 = sc.nextLine();

        while (matcher.find())
            System.out.println(str1.substring(matcher.start(), matcher.end())
                    + "*");

        count++;
    }
}

I wanted to get the uppercase characters in the string and also their amount.

3ventic
  • 1,023
  • 1
  • 20
  • 32
Anuj
  • 29
  • 1
  • 6

4 Answers4

2

You can try with:

String uppers = str1.replaceAll("[^A-Z]", "");
int length    = uppers.length();
hsz
  • 148,279
  • 62
  • 259
  • 315
0

This:

    String str1 = "";
    Matcher matcher = pattern.matcher(str1);
    int count = 0;

    System.out.println("ENTER A SENTENCE");
    str1 = sc.nextLine();

    while (matcher.find())

will not work like you think. You match on the empty string. It doesn't matter that you re-assing str1 later.

Move the line

    Matcher matcher = pattern.matcher(str1);

just before the while loop, when your str1 variable references the string you really want to match, e.g. the user's input.

In addition, you want to remove the + sign from your regex, as it macthes consecutive sequences of upper case letters at once.

Ingo
  • 36,037
  • 5
  • 53
  • 100
  • @anuj Just increase the counter on each macth. Note that in the code you posted, the counter gets incremented only once after the macthings. (Use `while (...) { ... }`) – Ingo Mar 06 '14 at 10:13
0

You can use string intersection (Intersection of two strings in Java) using originalString & originalString.toUpperCase().

Community
  • 1
  • 1
nablex
  • 4,635
  • 4
  • 36
  • 51
0

Simply use the old way of converting the string in char array using toCharArray method of String and then simply iterating the array. Check in each iteration if the char is in the range of 65 to 90 [ ASCII value of A is 65 and Z is 90]. Increment for each true case.

nits.kk
  • 5,204
  • 4
  • 33
  • 55