How to count number of letters in sentence - java

I'm looking for simple way to find the amount of letters in a sentence.
All I was finding during research were ways to find a specific letter, but not from all kinds.
How I do that?
What I currently have is:
sentence = the sentence I get from the main method
count = the number of letters I want give back to the main method
public static int countletters(String sentence) {
// ....
return(count);
}

You could manually parse the string and count number of characters like:
for (index = 1 to string.length()) {
if ((value.charAt(i) >= 'A' && value.charAt(i) <= 'Z') || (value.charAt(i) >= 'a' && value.charAt(i) <= 'z')) {
count++;
}
}
//return count

A way to do this could stripping every unwanted character from the String and then check it's length. This could look like this:
public static void main(String[] args) throws Exception {
final String sentence = " Hello, this is the 1st example sentence!";
System.out.println(countletters(sentence));
}
public static int countletters(String sentence) {
final String onlyLetters = sentence.replaceAll("[^\\p{L}]", "");
return onlyLetters.length();
}
The stripped String looks like:
Hellothisisthestexamplesentence
And the length of it is 31.
This code uses String#replaceAll which accepts a Regular Expression and it uses the category \p{L} which matches every letter in a String. The construct [^...] inverts that, so it replaces every character which is not a letter with an empty String.
Regular Expressions can be expensive (for the performance) and if you are bound to have the best performance, you can try to use other methods, like iterating the String, but this solution has the much cleaner code. So if clean code counts more for you here, then feel free to use this.
Also mind that \\p{L} detects unicode letters, so this will also correctly treat letters from different alphabets, like cyrillic. Other solutions currently only support latin letters.

SMA's answer does the job, but it can be slightly improved:
public static int countLetters(String sentence) {
int count = 0;
for (int i = 0; i < sentence.length; i ++)
{
char c = Character.toUpperCase(value.charAt(i));
if (c >= 'A' && c <= 'Z')
count ++;
}
return count;
}

This is so much easy if you use lambda expression:
long count = sentence.chars().count();
working example here: ideone

use the .length() method to get the length of the string, the length is the amount of characters it contains without the nullterm
if you wish to avoid spaces do something like
String input = "The quick brown fox";
int count = 0;
for (int i=0; i<input.length(); i++) {
if (input.charAt(i) != ' ') {
++count;
}
}
System.out.println(count);
if you wish to avoid other white spaces use a regex, you can refer to this question for more details

import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
String str = sc.nextLine();
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (Character.isLetter(str.charAt(i)))
count++;
}
System.out.println(count);
}
}

Related

What is the best way to replace a letter with the letter following it in the alphabet in Java?

I'm a programming newbie and I am doing a coderbyte exercise that says "
Replace every letter in the string with the letter following it in the alphabet (ie. c becomes d, z becomes a)"
i'm thinking of the following methods:
declare a string called "abcdefghijklmnopqrstuvxyz" and compare each string's char index position with the alphabet's index position, and then just bring the alphabet char that is located at the i+1 index location. But I don't know how it would work from z to a.
I've seen some techniques using ASCII values for every char but I've never done that before and not sure how it works
convert the given string into a char[] array, but then I'm not sure how I would tell the system to get me the next alphabet char
What would be the easiest way to do this?
EDIT
this is my code so far, but it doesn't work.
import java.util.*;
import java.io.*;
class Main {
public static String LetterChanges(String str) {
// code goes here
String alphabet = "abcdefghijklmnopqrstuvwxyz";
String newWord = "";
for (int i = 0; i < str.length(); i++){
for (int j = 0; j < alphabet.length(); i++){
if (str[i] == alphabet[i]){
if (alphabet[i+1].isVowel()){
newWord = newWord + toUpperCase(alphabet[i+1]);
}
else{
newWord = newWord + alphabet[i+1];
}
}
}
}
return str;
}
public static void main (String[] args) {
// keep this function call here
Scanner s = new Scanner(System.in);
System.out.print(LetterChanges(s.nextLine()));
}
}
Can't I ask for the index position of a Char that is a part of a String? in C I could do that.
Other than that not sure why it doesn't work.
I would definitely go with method 1.
I believe what you're looking for is the indexOf method on a String.
First of, I would create a method that given a character finds the next letter in the alphabet and return that. This could be done by finding the letter in your alphabet string and then fetch the letter at index+1. As you also pointed out you would need to take care of the edge case to turn 'z' into 'a', could by done with an if-statement or by having an extra letter 'a' at the end of your alphabet string.
Now all that remains to do is create a loop that runs over all characters in the message and calls the previously made method on that character and constuct a new string with the output.
Hope this helps you figure out a solution.
Assuming that there would be only lower case English letters in the given String the most performant way would be to add +1 to every character, and use either if-statement checking whethe the initial character was z or use the modulo operator % as #sp00m has pointed out in the comment.
Performing a search in the alphabetic string (option 1 in your list) is redundant, as well extracting array char[] from the given string (option 3).
Checking the edge case:
public static String shiftLetters(String str) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char next = str.charAt(i);
if (next == 'z') result.append('a'); // checking the edge case
else result.append((char) (next + 1));
}
return result.toString();
}
Applying modulo operator:
public static String shiftLetters(String str) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char next = (char) ((str.charAt(i) - 'a' + 1) % 26 + 'a');
result.append(next);
}
return result.toString();
}
main()
public static void main(String[] args) {
System.out.println(shiftLetters("abc"));
System.out.println(shiftLetters("wxyz"));
}
Output:
bcd // "abc"
xyza // "wxyz"

How to check if a String contains 3 digits or more

I'm currently trying to check if a string contains 3 digits or more. If it does, then it is valid. How can I fix it?
System.out.print("Enter a string: "); //111Hello <-- valid
String word = input.nextLine();
boolean numbers = word.matches(".*\\d{3,}");
System.out.println(numbers);
Output:
Invalid
Here are some examples:
Input:
Hello244
Output:
Valid
Input:
3Hello
Output:
Invalid
Input:
6Hello2Hello5
Output:
Valid
This is easy to do using a regular expression, because the set of strings containing at least three digits is a regular language - precisely what regular expressions are designed to recognise.
public boolean hasThreeDigits(String s) {
return s.matches(".*\\d.*\\d.*\\d.*");
}
The regex .*\d.*\d.*\d.* matches three digits with anything before, after or in between.
Let's do this with regular expressions. That doesn't really seem required, but let's assume this is an assignment:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class FindDigits {
public static final Pattern DIGIT_PATTERN = Pattern.compile("\\p{Digit}");
private static int countDigits(String input) {
final Matcher m = DIGIT_PATTERN.matcher(input);
int c = 0;
while (m.find()) {
c++;
}
return c;
}
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
final int c = countDigits(args[i]);
System.out.printf("Input : \"%s\"%nOutput: %s%n", args[i], c >= 3 ? "Valid" : "Invalid");
}
}
}
This answer assumes that the input is a set of strings on the command line. It defines a function to count the occurrences of pattern consisting of a single digit. It could of course stop counting at 3.
I'm mainly posting this because Matcher.find is often overlooked as it doesn't have a convenience method defined in String. It often makes for much easier to read regular expressions as you don't need to define what you are not looking for. Otherwise you're stuck with regular expressions strings such as ".*\\d.*\\d.*\\d.*" which are kind of horrible and do not scale well.
Instead of the while loop you can also use m.results().count() on a later version of the Java runtime. In that case a one-liner would be:
long count = Pattern.compile("\\p{Digit}").matcher(input).results().count();
Why not have a counter and loop over each character and then test if its a digit?
This is pseudo code :
System.out.print("Enter a string: "); //111Hello <-- valid
String word = input.nextLine();
int numberOfDigits = countDigits(word, 3);
if (numberOfDigits) >= 3{//...
int countDigits(String val, int max){
int cnt = 0;
for(int i =0; i < val.length(); i++){
char c = val.charAt(i);
if(Character.isDigit(c){
cnt++;
}
if(cnt == max)return;
}
return cnt;
}
https://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#isDigit(char)
Maybe not the most elegant solution, but pretty short and straightforward:
System.out.println(input.replaceAll("\\D","").length() > 2);
I prefer kaya3's solution the most

Print vowels from a word in Java

I am a beginner at java and I am doing this course an needed some help with this. Basically, a user will input a string and then the program will print out only the vowels on one line.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
System.out.print("In:");
String word = inp.nextLine();
//write your code below
for(int whatsat = 0; whatsat < word.length(); whatsat++){
if (word.charAt(whatsat).equals("a")){ //how to declare mutiple letters?
System.out.print(word.charAt(whatsat));
}
}
}
}
I agree with #Logan. You don't use equals() to compare primitive type values (int, char, boolean, etc.), just use simple == expression.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
System.out.print("In:");
String word = inp.nextLine();
//write your code below
for(int whatsat = 0; whatsat < word.length(); whatsat++){
char c = Character.toLowerCase(word.charAt(whatsat));
if (c == 'a' || c == 'e'|| c == 'i' || c == 'o' || c == 'u'){
System.out.print(word.charAt(whatsat));
}
}
}
}
A simple way to do this (intentionally avoiding complex regex options) would be to use the String.indexOf() method within your loop.
In the example below, we basically check if "AEIOUaeiou" contains the char that we're pulling from the user's input. If so, we extract it:
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
System.out.print("In:");
String word = inp.nextLine();
//write your code below
// This will hold any matching vowels we find
StringBuilder sb = new StringBuilder();
for (int i = 0; i < word.length(); i++) {
// Check if our list of vowels contains the current char. If the current char exists in the String of vowels, it will have an index of 0 or greater.
if ("AEIOUaeiou".indexOf(word.charAt(i)) > -1) {
// If so, add it to our StringBuilder
sb.append(word.charAt(i));
}
}
// Finally, print the result
System.out.println(sb.toString());
}
The Result:
With test input of "This is my test input. Did it work?" the output is: iieiuiio
So there's two issues here:
Characters are compared differently from Strings.
Checking for multiple characters.
To compare characters, do something like:
if (word.charAt(whatsat) == 'a') {
...
}
Note the single quotes! 'a' not "a"!
If you're asking "why are comparisons for strings and characters different?", that's a good question. I actually don't know the reason, so we should both research it. Moving on.
To check for multiple characters:
for(int whatsat = 0; whatsat < word.length(); whatsat++){
if (word.charAt(whatsat) == 'a' || word.charAt(whatsat) == 'e' || word.charAt(whatsat) == 'i'){
System.out.print(word.charAt(whatsat));
}
}
Note that if you're input has capital letters, you'll need to either:
Convert your input to lowercase so you can just check for lowercase letters, or
Explicitly check for capital letters in your if statement, e.g
if (...word.charAt(whatsat) == 'A' ...)
Longterm, you'll want to research regular expressions like a Adrian suggested in the comments. It may be complicated for a beginning student, but if you're interested you should look into it.
Hope this helps.
I am really surprised nobody has suggested using Enums... Cleanest way and simplest way, in my opinion.
Simply define an Enum with all the vowels, go through the String and compare each character to the values inside of Enum, ignoring the case - note the cast of char into String. If it is present in the Enum, print it out.
public class VowelFind {
enum Vowels {
A, E, I, O, U
}
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
System.out.print("In:");
String word = inp.nextLine();
for (int i = 0; i < word.length(); i++) { //loop through word
for (Vowels v : Vowels.values()) { //loop through Enum values
if((word.charAt(i)+"").equalsIgnoreCase(v.name())) { //compare character to Enum value, ignoring case
System.out.print(word.charAt(i));
}
}
}
}
}
Input: Hello World
Output: eoo
I prefer to use Hashmap as lookup is O(1)
public class PrintVowelsInWord {
public static Map<Character, Character> vowels;
public static void main(String[] args) {
loadMap();
// for simplicity sake I am not using Scanner code here
getVowels("wewillrockyou");
}
public static void loadMap() {
if (vowels == null) {
vowels = new HashMap<>();
vowels.put('a', 'a');
vowels.put('e', 'e');
vowels.put('i', 'i');
vowels.put('o', 'o');
vowels.put('u', 'u');
}
}
public static void getVowels(String input) {
for (Character letter : input.toCharArray()) {
if (vowels.containsKey(letter)) {
System.out.print(letter);
}
}
}
}

Counting Everything Besides Characters in Java

I need to print every character except letters. (commas, spaces, ect.) and display them. Here is the code thus far,
public static void main(String[] args)
{
String a = "elephant";
String b = "ElEphAnt";
String c = "This is a string.";
String d = "i R gr8, u R gr8";
int ucounter = 0;
int lcounter = 0;
int dcounter = 0;
int ocounter = 0;
for (int i = 0; i < a.length(); i++)
{
if (Character.isUpperCase(a.charAt(i)))
ucounter++;
if (Character.isLowerCase(a.charAt(i)))
lcounter++;
if (Character.isDigit(a.charAt(i)))
dcounter++;
}
System.out.println("String: " + a );
System.out.println("\n");
System.out.println("\tlowercase: %d, uppercase: %d, digit: %d, other: " +ucounter);
}
I am having a small issue getting them to print out the numbers after calculating them, but that is a separate issue I will solve on my own. I have perused the forums and cannot seem to find how I count white space and special characters. I am only allowed to use length() and charAt() for this. What is the Character.is?? for special characters? Or is there even one?
Instead of just using if's, use if/else combinations, so that you can make sure you're always only running into one matching case. Then, use Character.isWhitespace to detect white space, and finally !Character.isLetter (note the !) to detect everything except letters.
It's important that you do this with if/elses or else the last test will match for digits, commas, whitespace, etc. too.
From class documentation for java.lang.Character.isLetter:
A character is considered to be a letter if its general category type, provided by getType(codePoint), is any of the following:
UPPERCASE_LETTER
LOWERCASE_LETTER
TITLECASE_LETTER
MODIFIER_LETTER
OTHER_LETTER
You can use !(Character.isLetter(c) || Character.isDigit(c)) operations. This will print non-alphanumeric characters.
public class Tester {
public static void main(String[] args) {
String str = "fkgajsf783 yrW^R^.,,";
//str = str.replaceAll("\\s", ""); // if you do not want to white space, use this line;
int count = 0;
for (char c : str.toCharArray()) {
if (!(Character.isLetter(c) || Character.isDigit(c))) {
System.out.println(c);
count++;
}
}
System.out.println(count);
}
}
prints:
// White space
^
^
.
,
,
6

Regular Expressions to count number of ocurrences of a string in Java

I'm learning Java as I complete CodingBat exercises, and I want to start using regular expressions to solve some level 2 String problems. I'm currently trying to solve this problem:
Return the number of times that the string "code" appears anywhere in the given string, except we'll accept any letter for the 'd', so "cope" and "cooe" count.
countCode("aaacodebbb") → 1
countCode("codexxcode") → 2
countCode("cozexxcope") → 2
And here is the piece of code I wrote (which doesn't work, and I'd like to know why):
public int countCode(String str) {
int counter = 0;
for (int i=0; i<str.length()-2; i++)
if (str.substring(i, i+3).matches("co?e"))
counter++;
return counter;
}
I'm thinking that maybe the matches method isn't compatible with substring, but I'm not sure.
You need to use the regular expression syntax. In this case you want "co\\we", where \\w means any letter.
BTW you can do
public static int countCode(String str) {
return str.split("co\\we", -1).length - 1;
}
Try using this in the if statement. Unless I'm mixing up Java rules with PHP, then it needs to be +4 rather than +3.
str.substring(i, i+4)
public int countCode(String str) {
int count=0; // created a variable to count the appearance of "coe" in the string because d doesn't matter.
for(int i=0;i<str.length()-3;i++){
if(str.charAt(i)=='c'&&str.charAt(i+1)=='o'&&str.charAt(i+3)=='e'){
++count; // increment count if we found 'c' and 'o' and 'e' in the string.
}
}
return count; // returing the number of count 'c','o','e' appeared in string.
}
public class MyClass {
public static void main(String[] args) {
String str="Ramcodecopecofeacolecopecofeghfgjkfjfkjjcojecjcj BY HARSH RAJ";
int count=0;
for (int i = 0; i < str.length()-3; i++) {
if((str.substring(i, i+4)).matches("co[\\w]e")){
count++;
}
}
System.out.println(count);
}
}

Categories

Resources