How to count uppercase and lowercase letters in a string? - java

yo, so im trying to make a program that can take string input from the user for instance: "ONCE UPON a time" and then report back how many upper and lowercase letters the string contains:
output example: the string has 8 uppercase letters
the string has 5 lowercase letters, and im supposed to use string class not arrays, any tips on how to get started on this one? thanks in advance, here is what I have done so far :D!
import java.util.Scanner;
public class q36{
public static void main(String args[]){
Scanner keyboard = new Scanner(System.in);
System.out.println("Give a string ");
String input=keyboard.nextLine();
int lengde = input.length();
System.out.println("String: " + input + "\t " + "lengde:"+ lengde);
for(int i=0; i<lengde;i++) {
if(Character.isUpperCase(CharAt(i))){
}
}
}
}

Simply create counters that increment when a lowercase or uppercase letter is found, like so:
for (int k = 0; k < input.length(); k++) {
/**
* The methods isUpperCase(char ch) and isLowerCase(char ch) of the Character
* class are static so we use the Class.method() format; the charAt(int index)
* method of the String class is an instance method, so the instance, which,
* in this case, is the variable `input`, needs to be used to call the method.
**/
// Check for uppercase letters.
if (Character.isUpperCase(input.charAt(k))) upperCase++;
// Check for lowercase letters.
if (Character.isLowerCase(input.charAt(k))) lowerCase++;
}
System.out.printf("There are %d uppercase letters and %d lowercase letters.",upperCase,lowerCase);

java 8
private static long countUpperCase(String inputString) {
return inputString.chars().filter((s)->Character.isUpperCase(s)).count();
}
private static long countLowerCase(String inputString) {
return inputString.chars().filter((s)->Character.isLowerCase(s)).count();
}

The solution in Java8:
private static long countUpperCase(String s) {
return s.codePoints().filter(c-> c>='A' && c<='Z').count();
}
private static long countLowerCase(String s) {
return s.codePoints().filter(c-> c>='a' && c<='z').count();
}

You can try the following code :
public class ASCII_Demo
{
public static void main(String[] args)
{
String str = "ONCE UPON a time";
char ch;
int uppercase=0,lowercase=0;
for(int i=0;i<str.length();i++)
{
ch = str.charAt(i);
int asciivalue = (int)ch;
if(asciivalue >=65 && asciivalue <=90){
uppercase++;
}
else if(asciivalue >=97 && asciivalue <=122){
lowercase++;
}
}
System.out.println("No of lowercase letter : " + lowercase);
System.out.println("No of uppercase letter : " + uppercase);
}
}

Use regular expressions:
public Counts count(String str) {
Counts counts = new Counts();
counts.setUpperCases(str.split("(?=[A-Z])").length - 1));
counts.setLowerCases(str.split("(?=[a-z])").length - 1));
return counts;
}

import java.io.*;
import java.util.*;
public class CandidateCode {
public static void main(String args[] ) throws Exception {
int count=0,count2=0,i;
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
int n = s.length();
for( i=0; i<n;i++){
if(Character.isUpperCase(s.charAt(i)))
count++;
if(Character.isLowerCase(s.charAt(i)))
count2++;
}
System.out.println(count);
System.out.println(count2);
}
}

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, please try to import the least number of libraries. So, avoid using .* as much as you can.
import java.util.Scanner;
public class q36 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Give a string ");
String input = keyboard.nextLine();
int numberOfUppercaseLetters =
Long.valueOf(input.chars().filter(c -> Character.isUpperCase(c)).count())
.intValue();
int numberOfLowercaseLetters =
Long.valueOf(input.chars().filter(c -> Character.isLowerCase(c)).count())
.intValue();
System.out.println("The lenght of the String is " + input.length()
+ " number of uppercase letters " + numberOfUppercaseLetters
+ " number of lowercase letters " + numberOfLowercaseLetters);
}
}
Sample input:
saveChangesInTheEditor
Sample output:
The lenght of the String is 22 number of uppercase letters 4 number of lowercase letters 18

You simply loop over the content and use the Character features to test it. I use real codepoints, so it supports supplementary characters of Unicode.
When dealing with code points, the index cannot simply be incremented by one, since some code points actually read two characters (aka code units). This is why I use the while and Character.charCount(int cp).
/** Method counts and prints number of lower/uppercase codepoints. */
static void countCharacterClasses(String input) {
int upper = 0;
int lower = 0;
int other = 0;
// index counts from 0 till end of string length
int index = 0;
while(index < input.length()) {
// we get the unicode code point at index
// this is the character at index-th position (but fits only in an int)
int cp = input.codePointAt(index);
// we increment index by 1 or 2, depending if cp fits in single char
index += Character.charCount(cp);
// the type of the codepoint is the character class
int type = Character.getType(cp);
// we care only about the character class for lower & uppercase letters
switch(type) {
case Character.UPPERCASE_LETTER:
upper++;
break;
case Character.LOWERCASE_LETTER:
lower++;
break;
default:
other++;
}
}
System.out.printf("Input has %d upper, %d lower and %d other codepoints%n",
upper, lower, other);
}
For this sample the result will be:
// test with plain letters, numbers and international chars:
countCharacterClasses("AABBÄäoßabc0\uD801\uDC00");
// U+10400 "DESERET CAPITAL LETTER LONG I" is 2 char UTF16: D801 DC00
Input has 6 upper, 6 lower and 1 other codepoints
It count the german sharp-s as lowercase (there is no uppercase variant) and the special supplement codepoint (which is two codeunits/char long) as uppercase. The number will be counted as "other".
Using Character.getType(int cp) instead of Character.isUpperCase() has the advantage that it only needs to look at the code point once for multiple (all) character classes. This can also be used to count all different classes (letters, whitespace, control and all the fancy other unicode classes (TITLECASE_LETTER etc).
For a good background read on why you need to care about codepoints und units, check out: http://www.joelonsoftware.com/articles/Unicode.html

Related

How do I write a converting (lowercase->uppercase, single digits->double its value, two digits->sum of its digits) program w/ letters & numbers?

I was tasked to write a function that takes in user input as a string. For all characters which are numeric, double its value and, if it is
two digits, then replace it with the sum of its digits (e.g., 6 → 12 → 3 whereas 3 → 6). For all characters which are in uppercase, replace it with lowercase. For all characters which are in lowercase, replace it with uppercase (e.g., m → M and N → n). The program should keep asking the user to enter strings until they either enter ‘q’ or
‘Q’ to quit.
I have this so far, which works for the conversion of the letters. I'm not sure how to implement the other part into it and where it would go.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String str1;
System.out.print("Enter string: ");
str1 = scan.nextLine();
StringBuffer newStr = new StringBuffer(str1);
for (int i = 0; i < str1.length(); i++) {
//Checks for lower case character
if (Character.isLowerCase(str1.charAt(i))) {
//Convert it into upper case using toUpperCase() function
newStr.setCharAt(i, Character.toUpperCase(str1.charAt(i)));
}
//Checks for upper case character
else if (Character.isUpperCase(str1.charAt(i))) {
//Convert it into upper case using toLowerCase() function
newStr.setCharAt(i, Character.toLowerCase(str1.charAt(i)));
}
}
System.out.println("String after conversion : " + newStr);
}
}
here is my approach
public static String conversion(String inputString){
String out = "";
for(char c:inputString.toCharArray()){
if(Character.isDigit(c)){
int num = Integer.parseInt(String.valueOf(c))*2;
if(num>=10){
char[] parts = String.valueOf(num).toCharArray();
int sum = 0;
sum+=Integer.parseInt(String.valueOf(parts[0]));
sum+=Integer.parseInt(String.valueOf(parts[1]));
out+=sum;
}else out+=num;
}else{
if(Character.isUpperCase(c)) out+=Character.toLowerCase(c);
else out+=Character.toUpperCase(c);
}
}
return out;
}

Im having a problem with finding the palindrome of a upper case and lower case version of a word

So, I'm meant to get two version of a word given by user input, a version with just the lower case letters and then a version with just the upper case letters. Im then meant to find out if both of the words are palindromes. For example if the word was 'HEllO', the words HEO and ll would be created and then the output "HEO is not a palindrome, ll is a palindrome" would be printed. Im pretty sure my code makes sense but it won't say if either version of the original word is a palindrome. The following is the code.
public class comp1
{
public static void main(String []args)
{
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String lower = lowerCaseLetters(input);
String upper = upperCaseLetters(input);
palindromeUpper(upper);
palindromeLower(lower);
}
public static String lowerCaseLetters(String input)
{
char[] ar = new char[input.length()];
for(int i = 0; i < input.length(); i++)
{
if(Character.isLowerCase(input.charAt(i)))
{
ar[i] = input.charAt(i);
}
}
String lowercase = new String(ar);
return lowercase;
}
public static String upperCaseLetters(String input)
{
char[] ar = new char[input.length()];
for(int i = 0; i < input.length(); i++)
{
if(Character.isUpperCase(input.charAt(i)))
{
ar[i] = input.charAt(i);
}
}
String uppercase = new String(ar);
return uppercase;
}
public static void palindromeUpper(String sent)
{
String reverse = "";
for(int i = sent.length()-1; i >= 0; i--)
{
reverse += sent.charAt(i);
}
if(sent.equals(reverse))
{
System.out.println("Upper case " + sent + " is a palindrome");
}
else
{
System.out.println("Upper case " + sent + " is not a palindrome");
}
}
public static void palindromeLower(String sent)
{
String reverse = "";
for(int i = sent.length()-1; i >= 0; i--)
{
reverse += sent.charAt(i);
}
if(sent.equals(reverse))
{
System.out.println("Lower case " + sent + " is a palindrome");
}
else
{
System.out.println("Lower case " + sent + " is not a palindrome");
}
}
}```
arrays don't skip 'empty' values. In fact, there's no such thing as an empty slot; char[] ar = new char[input.length()]; gives you a char array with length slots, and each slot is filled with an actual character: The NUL character.
You then copy over all lowercase letters to their appropriate position, which means all non-lowercase letters still have the NUL character. You then turn this back into a string, which will be a string with lots of NUL characters, and those NUL characters will then prevent the rest of your code from working properly; ll is a palindrome, sure. but \0\0ll\0 is not.
You can't resize arrays, you need to create them at the right size. Thus, you have two options:
loop through the string twice. First time, you just count lowercase letters, that is all you do. Second time, you copy over the lowercase letters, and not to position i, but to a counter you maintain (the first l occurs at i=2, but needs to go into ar[0]. The second l occurs at i=3, and needs to go into ar[1]).
Don't use a char array; use a StringBuilder instead, which grows on demand. just .append any lowercase letters.
2 is probably easier, but involves the use of another class (java.lang.StringBuilder).
Note then that your palindromeLower and palindromeUpper methods are identical, other than the messaging.

Can't figure out what is wrong with my code

This is the instructions i got from my teacher:
Write your code in the file WordCount.java. Your code should go into a method with the following signature. You may write your own main method to test your code. The graders will ignore your main method:
public static int countWords(String original, int minLength){}
Your method should count the number of words in the sentence that meet or exceed minLength (in letters). For example, if the minimum length given is 4, your program should only count words that are at least 4 letters long.
Words will be separated by one or more spaces. Non-letter characters (spaces, punctuation, digits, etc.) may be present, but should not count towards the length of words.
Hint: write a method that counts the number of letters (and ignores punctuation) in a string that holds a single word without spaces. In your countWords method, break the input string up into words and send each one to your method.
This is my code:
public class WordCount {
public static void main(String[] args)
{
System.out.print("Enter string: ");
String input = IO.readString();
System.out.print("Enter minimum length for letter: ");
int length = IO.readInt();
IO.outputIntAnswer(countWords(input, length));
}
public static int countWords(String original, int minLegth)
{
int count = 0;
int letterCount = 0;
for(int i = 0; i < original.length(); i++)
{
char temp = original.charAt(i);
if(temp >= 'A' && temp <= 'Z' || temp >= 'a' && temp <= 'z')
{
letterCount++;
}
else if(temp == ' '|| i == original.length()-1)
{
if(letterCount >= minLegth)
{
count++;
}
letterCount = 0;
}
}
return count;
}
}
My college uses an autograder to grade project and i am keep getting one of the test case wrong. Can someone help me figure out what the problem is?
I figured the problem that your code is not able to compare the last character.It expects a space after the last character so that it can compare the last character since java doesn't use null character terminator for string termination.I have emulated the same code using Scanner class as I was having some trouble with io.So I have done the following change:
Scanner sc1,sc2;
sc1=new Scanner(System.in);
String input = sc1.nextLine()+" ";
I don't know if its possible to do:
String input = IO.readString()+" ";
but i think you should try appending blank space " " at the end of the string

How to print out the number of capital letters in a string - java

So I have this program I need to write. I'm, supposed to get an input string from a user and then print out how many capital letters and how many lowercased letters are in the string. I've looked everywhere in the book that I have and I just can't seem to find anything about how to print out the uppercase and lowercase letters. I've been doing a lot of googling as well and I couldn't find anything useful.
Anyway here's my code:
import java.util.Scanner; //calls out the method to get input from user
public class Verk1 {
public static void main(String args[])
{
Scanner innslattur = new Scanner(System.in); //input gotten from user
System.out.println("Sláðu inn textabrot í há- og lágstöfum.");
System.out.println("Forritið mun þá segja þér hve margir stafir eru af hverri gerð.");
System.out.println("Textabrot: ");
//The printouts before tell the user to enter in a string, the program will then print out //how many upper- and lowercase letters there are.
String strengur = innslattur.nextLine();
String hastafir = "";
for (int i=0; i<hastafir.length();i++);
{
System.out.println("Í textabrotinu eru " + hastafir + " hástafir");
}
}
}
I know the code is faulty/doesn't work, but do any of you know how I get the number of uppercase- lowercase letters to print them out?
Thanks in advance!
Cheers
I haven't tested it but I would look to do something like this.
String text = "This IS My TEXT StrinG";
int upperCaseCounter = 0;
int lowerCaseCounter = 0;
for (int i=0; i<text.length(); i++)
{
if (Character.isUpperCase(text.charAt(i)))
{
upperCaseCounter++;
}
else if(Character.isLowerCase(text.charAt(i)))
{
lowerCaseCounter++;
}
}
System.out.println("Total Uppercase Characters: " + upperCaseCounter);
System.out.println("Total Lowercase Characters: " + lowerCaseCounter);
You can do their fairly easily if you convert the string to a char[] first. You can then use the isUpperCase(char c) for each character in the string. http://www.tutorialspoint.com/java/character_isuppercase.htm
For some strange reason your for loop is referring to an empty string you've just declared, rather than the string you just read in from the user. However, if you change that, inside your loop you can get at the individual characters in the string with strengur.charAt(i) and you can test whether a letter is capital with Character.isUpperCase(ch) and you can check for a lower case letter with Character.isLowerCase(ch).
public void printCapsAndLowercaseCounts(String s) {
int uppercase = 0;
int lowercase = 0;
if (s != null) {
String s1 = s.toUpperCase();
String s2 = s.toLowerCase();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == s1.charAt(i) ^ s.charAt(i) == s2.charAt(i)) {
if (s.charAt(i) == s1.charAt(i)) uppercase++;
else lowercase++;
}
}
}
System.out.println(uppercase + " " + lowercase);
}
Seems like this would do the trick, assuming you're not doing it an excessive amount. Just use a temporary string, and get the difference between the two:
int capLetterCount = originalString.length() - originalString.replaceAll("[A-Z]", "").length();

Counting the number of occurences of characters in a string [duplicate]

This question already has answers here:
Java compressing Strings
(21 answers)
Closed 8 years ago.
I am trying to write a Java program which takes in as input a string and counts the number of occurrences of characters in a string and then prints a new string having the character followed by the no of occurrences.
E.G.
Input String:
aaaabb
Output String:
a4b2
Input String:
aaaaabbbc
Output String:
a5b3c1
I am posting my java code.
It is throwing StringOutOfBoundException
/*Write a routine that takes as input a string such as "aabbccdef" and o/p "a2b2c2def" or "a4bd2g4" for "aaaabddgggg".*/
import java.util.Scanner;
public class CountingOccurences {
public static void main(String[] args) {
Scanner inp= new Scanner(System.in);
String str;
char ch;
int count=0;
System.out.println("Enter the string:");
str=inp.nextLine();
while(str.length()>0)
{
ch=str.charAt(0);
int i=0;
while(str.charAt(i)==ch)
{
count =count+i;
i++;
}
str.substring(count);
System.out.println(ch);
System.out.println(count);
}
}
}
This is the problem:
while(str.charAt(i)==ch)
That will keep going until it falls off the end... when i is the same as the length of the string, it will be asking for a character beyond the end of the string. You probably want:
while (i < str.length() && str.charAt(i) == ch)
You also need to set count to 0 at the start of each iteration of the bigger loop - the count resets, after all - and change
count = count + i;
to either:
count++;
... or get rid of count or i. They're always going to have the same value, after all. Personally I'd just use one variable, declared and initialized inside the loop. That's a general style point, in fact - it's cleaner to declare local variables when they're needed, rather than declaring them all at the top of the method.
However, then your program will loop forever, as this doesn't do anything useful:
str.substring(count);
Strings are immutable in Java - substring returns a new string. I think you want:
str = str.substring(count);
Note that this will still output "a2b2a2" for "aabbaa". Is that okay?
public class StringTest{
public static void main(String[] args){
String s ="aaabbbbccccccdd";
String result="";
StringBuilder sb = new StringBuilder(s);
while(sb.length() != 0){
int count = 0;
char test = sb.charAt(0);
while(sb.indexOf(test+"") != -1){
sb.deleteCharAt(sb.indexOf(test+""));
count++;
}
//System.out.println(test+" is repeated "+count+" number of times");
result=result+test+count;
}
System.out.println(result);
}
}
I don't want to give out the full code. So I want to give you the challenge and have fun with it. I encourage you to make the code simpler and with only 1 loop.
Basically, my idea is to pair up the characters comparison, side by side. For example, compare char 1 with char 2, char 2 with char 3, and so on. When char N not the same with char (N+1) then reset the character count. You can do this in one loop only! While processing this, form a new string. Don't use the same string as your input. That's confusing.
Remember, making things simple counts. Life for developers is hard enough looking at complex code.
Have fun!
Tommy "I should be a Teacher" Kwee
if this is a real program and not a study project, then look at using the Apache Commons StringUtils class - particularly the countMatches method.
If it is a study project then keep at it and learn from your exploring :)
You should be able to utilize the StringUtils class and the countMatches() method.
public static int countMatches(String str,
String sub)
Counts how many times the substring appears in the larger String.
Try the following:
int count = StringUtils.countMatches("a.b.c.d", ".");
I think what you are looking for is this:
public class Ques2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine().toLowerCase();
StringBuilder result = new StringBuilder();
char currentCharacter;
int count;
for (int i = 0; i < input.length(); i++) {
currentCharacter = input.charAt(i);
count = 1;
while (i < input.length() - 1 && input.charAt(i + 1) == currentCharacter) {
count++;
i++;
}
result.append(currentCharacter);
result.append(count);
}
System.out.println("" + result);
}
}
Try this:
import java.util.Scanner;
/* Logic: Consider first character in the string and start counting occurrence of
this character in the entire string. Now add this character to a empty
string "temp" to keep track of the already counted characters.
Next start counting from next character and start counting the character
only if it is not present in the "temp" string( which means only if it is
not counted already)
public class Counting_Occurences {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("Enter String");
String str=input.nextLine();
int count=0;
String temp=""; // An empty string to keep track of counted
// characters
for(int i=0;i<str.length();i++)
{
char c=str.charAt(i); // take one character (c) in string
for(int j=i;j<str.length();j++)
{
char k=str.charAt(j);
// take one character (c) and compare with each character (k) in the string
// also check that character (c) is not already counted.
// if condition passes then increment the count.
if(c==k && temp.indexOf(c)==-1)
{
count=count+1;
}
}
if(temp.indexOf(c)==-1) // if it is not already counted
{
temp=temp+c; // append the character to the temp indicating
// that you have already counted it.
System.out.println("Character " + c + " occurs " + count + " times");
}
// reset the counter for next iteration
count=0;
}
}
}

Categories