How to count white spaces in a given argument? - java

I find it strange why spaceCount doesn't add up when the expression is "12 + 1". I get an output 0 for spaceCount even though it should be 2. Any insight would be appreciated!
public int countSpaces(String expr) {
String tok = expr;
int spaceCount = 0;
String delimiters = "+-*/#! ";
StringTokenizer st = new StringTokenizer(expr, delimiters, true);
while (st.hasMoreTokens()) {
if ((tok = st.nextToken()).equals(" ")) {
spaceCount++;
}
}
return spaceCount; // the expression is: 12 + 1, so this should return 2, but it returns 0;
}

Your code seems to be ok, but if you want to count spaces you can use this :
int count = str.length() - str.replace(" ", "").length();

A tokenizer is overkill (and doesn't really help you) for this problem. Just loop through all the characters and count the spaces:
public int countSpaces( String expr )
{
int count = 0;
for( int i = 0; i < expr.length(); ++i )
{
if( expr.charAt(i) == ' ' )
++count;
}
return count;
}

Another one line solution could be the following which also performs a NULL check to the string.
int spacesCount = str == null ? 0 : str.length() - str.replace(" ", "").length();

Can also use:
String[] strArr = st.split(" ");
if (strArr.length > 1){
int countSpaces = strArr.length - 1;
}

This will find white spaces, including special ones.
You can keep the pattern so you don't need to compile it every time. If just need to search for " ", a loop should do it instead.
Matcher spaces = Pattern.compile("\\s").matcher(argumentString);
int count = 0;
while (spaces.find()) {
count++;
}

Related

Count Words Using indexOf

I can't use arrays, only simple Java (if, for, while, substring, length, indexOf)
public int howManyWords(String s){
myString = "I have a dream";
int count = 1;
int length = 0;
while(count>=0){
count = myString.substring(String.valueOf(length),myString.indexOf(" "));
count++;
length = myString.indexOf(" ");
}
return count;
}
Should return 4
First of all, you made infinite loop, because count is 1, and you just increase it.
Second, you haven't even try to write this code in some IDE, because it would throw you a syntax error, because you are assigning string to int, when you do count = myString.substring()
So, instead of using count in loop, you can use myString.indexOf
something like this could work if you don't care what is going to happen with myString
int count = 0;
while(myString.indexOf(" ") >= 0) {
count++;
myString = myString.substring(myString.indexOf(" ") + 1)
}
return count;
Let's assume that the string you are testing does not contain leading or trailing spaces, because that affects the solution. The example string in your question does not contain leading or trailing spaces.
Simply call method indexOf(String, int) in a loop and in each iteration you set the int parameter to one more than what you got in the previous iteration. Once the value returned by method indexOf() is -1 (minus one), you are done. But don't forget to add the last word after you exit the loop.
String myString = "I have a dream";
int count = 0;
int index = 0;
while (index >= 0 && index < myString.length()) {
index = myString.indexOf(" ", index);
System.out.println("index = " + index);
if (index >= 0) {
index++;
count++;
}
}
if (index < 0) {
count++;
}
System.out.println("count = " + count);
Edited : Added missing else case.
Try the following code :
Remove the counted words from your string using the substring and indexOf, and increment the count in each iteration.
public int countWords(String s){
String myString = "I have a dream";
int count = 0;
int length = myString.length();
while(length>0){
if((myString.indexOf(" ")!=-1) && (myString.indexOf(" ")+1)<length){
myString = myString.subString(myString.indexOf(" ")+1);
count++;
length = myString.length();
}
else {
length = 0;
break;
}
}
return count;
}
PS: Conventionally, your method names should denote actions, hence I suggested it to be countWords instead of howManyWords.

How to count string from last 3rd comma in Java?

I am using String s="abc,def,hi,hello,lol"
By using Java, how we can split the string from the last 3rd comma and get the string and string count?
Need Output as:
,hi,hello,lol
And the count is 13.
Can you please guide me to better code?
Below is my code, but it removes String from the last 3rd comma.
String s ="abc,def,hi,hello,lol";
String[] split = s.split(",");
String newStr = "";
for(int i = 0 ; i < split.length -3 ; i++){
newStr += split[i] + ",";
}
newStr = newStr.substring(0, newStr.length() - 1);
System.out.println(newStr);
Look at String class API.
You can use lastIndexOf(String str, int fromIndex), substring(int beginIndex) and length() methods.
Follow below steps:
Call lastIndexOf 3 times and note down the return value.
Use substring to get string from this index.
Use length to get count.
Try this one,
String data ="abc,def,hi,hello,lol";
StringBuilder sb = new StringBuilder(data);
sb.reverse();
data= sb.toString();
List<String> split = new ArrayList<String>();
int startIndex = 0;
int n = 0;
for (int i = data.indexOf(',') + 1; i > 0; i = data.indexOf(',', i) + 1, n++) {
if (n % 3 == 2) {
split.add(data.substring(startIndex, i ));
startIndex = i;
}
}
split.add(data.substring(startIndex));
for(String s : split)
{
sb = new StringBuilder(s);
s = sb.reverse().toString();
System.out.println(s+" : "+s.length());
}
output :
,hi,hello,lol : 13
abc,def : 7
This one arrives at the answer in only two statements:
public static void main(String[] args) {
String s = "abc,def,hi,hello,lol";
String[] pieces = s.split("(?=,)"); // split using positive lookahead
String answer = (pieces.length < 3) ? "": // check if not enough pieces
Arrays.stream(pieces).skip(pieces.length - 3).collect(Collectors.joining());
System.out.format("Answer = \"%s\"%n", answer);
System.out.format("Count = %d%n", answer.length());
}
I split at the position before each comma using positive lookahead, because if you use a simple split(",") then your program would fail for strings that end with comma.
String output = s.substring(s.indexOf(",", 6));
System.out.println(" string from last 3rd comma -> "+ output +"\n and count -> "+ output.length() );
console output:
string from last 3rd comma -> ,hi,hello,lol and count -> 13

String Functions how to count delimiter in string line

I have a string line like the following :
A:B:C:D:E:F:G:H:I:J:K:L:M
It means delimiter ( : ) count is 12 . This line is valid.
Now suppose you have a following line :
A:B:C:D:E:F:G:H:::::
This line is also valid because it contains 12 delimiter . where 8 values are present and 4 values are blank.
Now the following line should be invalid :
A:B:C:D:E:F: -- Invalid - because it contains only 6 values but expected are 12.
how to do this .. ? I tried the following code , but not getting the desired output :
String strLine = "A:B:C:D:E:F:G:H:::::" ;
int delimiterCount = 12 ;
String[] ValuesArray = strLine.split(":");
if(ValuesArray.length != delimiterCounter){
System.out.println(Invalid);
}else {
System.out.println("ValidLine");
}
I am getting the output as Invalid where as it sould be Valid.
Use following method to count occurance of particular String
public static int countOccurance(String inputString, String key) {
int index = 0;
int fromIndex = 0;
int result = 0;
if (inputString == null || key == null) {
return 0;
}
while ((index = inputString.indexOf(key, fromIndex)) != -1) {
result++;
fromIndex = index + key.length();
}
return result;
}
If you want to use split, and it's not a bad approach really (although it might be for this particular situation), you need to pass -1 as the second argument to split otherwise it removes empty strings.
See http://ideone.com/gaUw5.
It is good to know this about split. Some languages require the -1 and some do not.
The code
class Main {
public static void main(String[] args) {
String line = "A:B:C:D:E:F:G:H:::::" ;
int delimiterCount = 12 ;
String[] values = line.split(":", -1);
if (values.length != delimiterCount + 1) {
System.out.println("Invalid Line");
} else {
System.out.println("Valid Line");
}
}
}
It should be
String strLine = "A:B:C:D:E:F:G:H: : : : : " ;
int delimiterCount = 12 ;
String[] ValuesArray = strLine.split(":");
if((ValuesArray.length - 1) != delimiterCounter){
System.out.println(Invalid);
}else {
System.out.println("ValidLine");
}
as array will have values not delimeter
No reason to use regex here. If the only criteria for checking the validity of an input is 12 delimeters :, just count them.
String strLine = "A:B:C:D:E:F:G:H:::::";
int EXPECTED_DELIMETERS = 12;
int delimiterCount = 0;
for (int idx = 0; idx < strLine.length(); idx++) {
if (strLine.charAt(idx) == ':') {
delimiterCount++;
}
}
if (EXPECTED_DELIMETERS == delimiterCount) {
System.out.println("ValidLine");
} else {
System.out.println("Invalid");
}
Concise Java 8 solution:
private static boolean isValid(String content, char delimiter, int count) {
return count == content.chars().filter(c -> c == delimiter).count();
}

Word count on Java

How can I count the words of a sentence given as string? We are allowed to use only the following: for loops, if statemant, while, charAt, length().
I wrote this code:
public static int getWordCount()
{
String data = "bla bla bla bla";
int Count = 0;
for (int i=0; i<data.length(); i++)
{
if (data.charAt(i) != ' ')
Count ++;
}
return Count;
}
But it counts only the letters and not the words.
Here's a suggestion: Count the number of ' ' and add 1?
Example:
"bla bla bla bla"
1 2 3 : 3 + 1 = 4
"hello"
: 0 + 1 = 1
If you want to get fancy you could keep a boolean variable named something like lastWasSpace, set it to true when running into a space, setting it to false when you run into a non-space character. If you only increment the Count when lastWasSpace is false, you'll be able to handle strings with multiple consecutive spaces as well.
"bla bla bla"
1 2 : 2 + 1 = 3
lastWasSpace: FFFFTTTFFFFTTTTTFFFF
the given code would indeed count letters and not words. You may want to change the condition to:
if (data.charAt(i) == ' ')
this means, if you find a space, this would mark the beginning of the next word. Also, the last word will not be counted so you should return Count+1 instead of Count.
There are several assumptions I made here:
There will be exactly one space in between words.
There will not be any leading or trailing spaces.
To consider multiple spaces between words, you would need to modify the code a little. Instead of checking if a character is space, check to see if a character is non-space and the previous character was either a space or no character for the case of first word. This would also handle leading and trailing spaces.
public class Main {
public static void main(String[] args) {
String data = "This is a Test";
int wordCount = 1;
int charCount = 0;
for (int i = 0; i < data.length(); i++) {
if (data.charAt(i) == ' ') {
wordCount++;
} else {
charCount++;
}
}
System.out.println("wordCount = " + wordCount);
System.out.println("charCount = " + charCount);
}
}
String ss = " leading spaces in string ";
String[] sa = ss.trim().split("\\w+");
System.out.println(sa.length);
Note the use of trim to handle surrounding whitespace.
Use the below code for count the words in the line,
int index = 0;
int numWords =0;
boolean prevwhitespace = true;
String line = "bla bla bla bla";
while(index < line.length())
{
char c = line.charAt(index++);
boolean currwhitespace = Character.isWhitespace(c);
if(prevwhitespace && !currwhitespace)
{
numWords++;
}
prevwhitespace= currwhitespace;
}
System.out.println("no. of words in the line :: " +numWords);
My solution:
public static int getWordCount() {
String data = "bla bla bla bla";
String[] arr = data.split(" ");
return arr.length;
}
String s = "Aljohani Abdallah";
int counter = 1;
for (int i = 0; i < s.length() - 1; i++) {
if (s.charAt(i) == ' ' && s.charAt(i + 1) != ' ')
counter++;
}
if (s == " ")
counter = 0;
System.out.println(counter);
this code above here is count number of words in String so the first thing I have to know is length of the string and then we do if condition, if i was in index equals space at the same time must the letter after space not equal space the add 1 to counter
the end if the String was empty the counter should be zero.
String str = " Hello there my name is Bill ";
str = str.trim();
int count = 0;
for(int i = 0; i<str.length(); i++) {
if(str.charAt(i) == ' ' && str.charAt(i-1) != ' ') {
count++;
}
}
System.out.println(count+1);

Find count of digits in string variable

I have a string which sometimes gives character value and sometimes gives integer value. I want to get the count of number of digits in that string.
For example, if string contains "2485083572085748" then total number of digits is 16.
Please help me with this.
A cleaner solution using Regular Expressions:
// matches all non-digits, replaces it with "" and returns the length.
s.replaceAll("\\D", "").length()
String s = "2485083572085748";
int count = 0;
for (int i = 0, len = s.length(); i < len; i++) {
if (Character.isDigit(s.charAt(i))) {
count++;
}
}
Just to refresh this thread with stream option of counting digits in a string:
"2485083572085748".chars()
.filter(Character::isDigit)
.count();
If your string gets to big and full of other stuff than digits you should try to do it with regular expressions. Code below would do that to you:
String str = "asdasd 01829898 dasds ds8898";
Pattern p = Pattern.compile("\d"); // "\d" is for digits in regex
Matcher m = p.matcher(str);
int count = 0;
while(m.find()){
count++;
}
check out java regex lessons for more.
cheers!
Loop each character and count it.
String s = "2485083572085748";
int counter = 0;
for(char c : s.toCharArray()) {
if( c >= '0' && c<= '9') {
++counter;
}
}
System.out.println(counter);
public static int getCount(String number) {
int flag = 0;
for (int i = 0; i < number.length(); i++) {
if (Character.isDigit(number.charAt(i))) {
flag++;
}
}
return flag;
}
in JavaScript:
str = "2485083572085748"; //using the string in the question
let nondigits = /\D/g; //regex for all non-digits
let digitCount = str.replaceAll(nondigits, "").length;
//counts the digits after removing all non-digits
console.log(digitCount); //see in console
Thanks --> https://stackoverflow.com/users/1396264/vedant for the Java version above. It helped me too.
int count = 0;
for(char c: str.toCharArray()) {
if(Character.isDigit(c)) {
count++;
}
}
Also see
Javadoc
Something like:
using System.Text.RegularExpressions;
Regex r = new Regex( "[0-9]" );
Console.WriteLine( "Matches " + r.Matches("if string contains 2485083572085748 then" ).Count );

Categories