Find count of digits in string variable - java

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 );

Related

How to count white spaces in a given argument?

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++;
}

Find the length of the longest substring with no consecutive repeating characters

In a recent interview, I was asked this to find the length of the longest sub-string with no consecutive repeating characters. This is different from the standard question, since it considers only consecutive repeating characters.
For example :
WOOD : 2
Italics : 7
This, of course, has to be done in O(N) time and space.
Go down the string character by character. Keep track of how many characters you've advanced without hitting a repeat in a var say "repeatcounter". If the next character matches the current character record the counter in a separate variable (only if it's bigger than what's already in there) and reset the repeatcounter.
In Python, I would approach it like this:
def interview(s):
current = longest = 0
for index, char in enumerate(s):
if index and char == s[index - 1]:
longest, current = max(longest, current), 0
current += 1
return max(longest, current)
public static void main(String[] args){
String s = "italics";
char[] c = s.toCharArray();
int tmp = 1;
for (int i = 1; i < s.length(); i++) {
if (c[i] == c[i-1]){
tmp = 0;
continue;
}
tmp++;
}
System.out.println(tmp);
}
output = 1
s = "italics"
output = 7
Hope the below code helps you. Thanks.
import java.util.HashSet;
public class SubString {
public static String subString(String input){
HashSet<Character> set = new HashSet<Character>();
String longestOverAll = "";
String longestTillNow = "";
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (set.contains(c)) {
longestTillNow = "";
set.clear();
}
longestTillNow += c;
set.add(c);
if (longestTillNow.length() > longestOverAll.length()) {
longestOverAll = longestTillNow;
}
}
return longestOverAll;
}
public static void main(String[] args) {
String input = "kaveeshkanwal abcvdghytrqp";//"substringfindout";
System.out.println(subString(input));
}
}

How to Split Complex String in java and how to sum values?

My String is like this
String myString= "3:2 2:26 1:11 8:4 4:25";
In this string I want to add all numbers occurring after ":" (and before the next whiteSpace). In this case Result is 2+26+11+4+25 = 68. How can I achieve this using Reg Expression?
My effort is:
if(a.contains(":")){
for(int i=0; i<a.length(); i++) {
if(a.contains(":")){
int indexOFColan= a.indexOf(":");
//System.out.println("indexOFColan:"+indexOFColan);
//int indexWhiteSpace = a.indexOf(" ");
String firstValue = String.valueOf(a.charAt((indexOFColan+1)));
System.out.println("FinalString:"+firstValue);
}
}
}
Works for me.
String in = "3:2 2:26 1:11 8:4 4:25";
String[] split = in.split(" ");
int sum = 0;
for(int i = 0; i < split.length; i++)
{
try {
sum += Integer.parseInt(split[i].split(":")[1]);
} catch(NumberFormatException e) {
System.out.println("Input not a number");
}
}
System.out.println(sum);
If you want to purely use regular expressions, the required expression is "\\d+:(\\d+)\\s*" (as a Java String).
Use Pattern#matcher method with find() to get the numbers you need:
int getSumofNumbersInComplexString(String my_string) {
int sum = 0;
Pattern p = Pattern.compile("\\d+:(\\d+)\\s*");
Matcher m = p.matcher(my_string);
while (m.find())
sum += Integer.parseInt(m.group());
return sum;
}
The above code should work for a string in the format you've specified. There are many other SO questions on regex matching, in case you want more details of how this works.

check how many times string contains character 'g' in eligible string

How we can check any string that contains any character how may time....
example:
engineering is a string contains how many times 'g' in complete string
I know this is and old question, but there is an option that wasn't answered and it's pretty simple one-liner:
int count = string.length() - string.replaceAll("g","").length()
Try this
int count = StringUtils.countMatches("engineering", "e");
More about StringUtils can be learned from the question: How do I use StringUtils in Java?
I would use a Pattern and Matcher:
String string = "engineering";
Pattern pattern = Pattern.compile("([gG])"); //case insensitive, use [g] for only lower
Matcher matcher = pattern.matcher(string);
int count = 0;
while (matcher.find()) count++;
Although Regex will work fine, but it is not really required here. You can do it simply using a for-loop to maintain a count for a character.
You would need to convert your string to a char array: -
String str = "engineering";
char toCheck = 'g';
int count = 0;
for (char ch: str.toCharArray()) {
if (ch == toCheck) {
count++;
}
}
System.out.println(count);
or, you can also do it without converting to charArray: -
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == toCheck) {
count++;
}
}
String s = "engineering";
char c = 'g';
s.replaceAll("[^"+ c +"]", "").length();
Use regex [g] to find the char and count the findings as below:
Pattern pattern = Pattern.compile("[g]");
Matcher matcher = pattern.matcher("engineering");
int countCharacter = 0;
while(matcher.find()) {
countCharacter++;
}
System.out.println(countCharacter);
If you want case insensitive count, use regex as [gG] in the Pattern.
use org.apache.commons.lang3 package for use StringUtils class.
download jar file and place it into lib folder of your web application.
int count = StringUtils.countMatches("engineering", "e");
You can try Java-8 way. Easy, simple and more readable.
long countOfA = str.chars().filter(ch -> ch == 'g').count();
this is a very very old question but this might help someone ("_")
you can Just simply use this code
public static void main(String[] args){
String mainString = "This is and that is he is and she is";
//To find The "is" from the mainString
String whatToFind = "is";
int result = countMatches(mainString, whatToFind);
System.out.println(result);
}
public static int countMatches(String mainString, String whatToFind){
String tempString = mainString.replaceAll(whatToFind, "");
//this even work for on letter
int times = (mainString.length()-tempString.length())/whatToFind.length();
//times should be 4
return times;
}
You can try following :
String str = "engineering";
int letterCount = 0;
int index = -1;
while((index = str.indexOf('g', index+1)) > 0)
letterCount++;
System.out.println("Letter Count = " + letterCount);
You can loop through it and keep a count of the letter you want.
public class Program {
public static int countAChars(String s) {
int count = 0;
for(char c : s.toCharArray()) {
if('a' == c) {
count++;
}
}
return count;
}
}
or you can use StringUtils to get a count.
int count = StringUtils.countMatches("engineering", "e");
This is an old question and it is in Java but I will answer it in Python. This might be helpful:
string = 'E75;Z;00001;'
a = string.split(';')
print(len(a)-1)

Validating an Array with least number of numeric Characters

I have an array of strings:
void populateStringArray()
{
toppings = new String[20];
toppings[0] = "Cheese12";
toppings[1] = "Pepperoni1234";
toppings[2] = "Black Olives1";
// ...
And I want to return the one with least numeric characters.
Can some one suggest the logic to achieve this?
If using Guava is an Option, you can just do this:
int digitChars = CharMatcher.DIGIT.countIn(yourString)
You can count the number of digits in a string str with
str.length() - str.replaceAll("\\d", "").length()
Simple as pie.
Now all you have to do is loop over your array toppings and find the string s for which str.length() - str.replaceAll("\\d", "").length() is least.
You can loop over characters and use Character.isDigit() to count digits in the string.
String str = "Cheese12";
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (Character.isDigit(str.charAt(i))) {
count++;
}
}
System.out.println(count);
Output:
2
Pattern p = Pattern.compile("-?\\d+"); //regex pattern to find integers on a string
int index = 0;
int test;
int lowest = Integer.MAX_VALUE;
for (int i : toppings.size()-1){
Matcher m = p.matcher(toppings[i]);
if (m.find()) { //assuming only one number to find
test = Integer.parseInt(m.group());
if (test < lowest){
lowest = test;
index = i;
}
}
}
return patterns[index]; //in case of tie the lowest index wins
You can find all digits in your string using regex and count the number of digits:
public int getNumberOfDigitsInString(String input) {
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(input);
int count = 0;
while (matcher.find())
count += matcher.group().length();
return count;
}
Now you can just iterate over your array and find the one with the least amount of digits:
int lowestN = Integer.MAX_VALUE;
String finalString = "";
for (String str:toppings) {
int currentN = getNumberOfDigitsInString(str);
if (lowestN > currentN) {
finalStr = str;
lowestN = currentN;
}
}
System.out.println("Result: " + finalStr + " (has " + lowestN + " digits in it)");
String leastChar(){
int leastChar=Integer.MAX_VALUE;
String leastTopping=null;
int eachToppingTemp=0;
for (String topping:toppings){
if (topping==null) continue;
eachToppingTemp= Integer.MAX_VALUE;
for (char eachChar:topping.toCharArray()){
if (Character.isDigit(eachChar)){
eachToppingTemp++;
}
}
if (eachToppingTemp<leastChar){
leastChar=eachToppingTemp;
leastTopping=topping;
}
}
System.out.println("Lowest char topping : "+leastTopping);
return leastTopping;
}

Categories