Validating an Array with least number of numeric Characters - java

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

Related

Java Program to get the sum of integers present in a string considering one of the integers is present in extreme end

I want to get the sum of integers present in the String "abc22gh20fg4". I want my output as 22+20+4=46.
I have written the code as below but it gives 22+20=44. It is not considering the number present in the very end.
public static void main(String[] args) {
String str = "abc22gh20fg4";
String num = "";
int sum = 0;
for (int i = 0; i < str.length(); i++) {
if (Character.isDigit(str.charAt(i))) {
num = num + str.charAt(i);
} else {
if (!num.equals("")) {
sum = sum + Integer.parseInt(num);
num = "";
}
}
}
System.out.println(sum);
}
I would go with split instead of deep for loop :
String str = "abc22gh20fg4";
String regex = "[^\\d]+"; // this will extract only digit
String[] strs = str.split(regex);
int sum = Arrays.stream(strs)
.filter(digits -> digits != null && !digits.equals(""))
.mapToInt(Integer::parseInt).sum();
System.out.println(sum);
If you want before java 8
String str = "abc22gh20fg4";
String regex = "[^\\d]+";
String[] strs = str.split(regex); // this will extract only digit
int sum = 0;
for (String digits:strs) { // iterate each digits
if (digits!=null && !digits.equals("")){ // check null or empty
sum += Integer.parseInt(digits); // parse and sum
}
}
System.out.println(sum);
Update:
Your actual problem is when you loop through all the character the last character is number . it exit the loop without sum so you need to check if it is last digit sum it .
public class Test {
public static void main(String[] args) {
String str = "abc22gh20fg4";
String num = "";
int sum = 0;
for (int i = 0; i < str.length(); i++) {
if (Character.isDigit(str.charAt(i))) {
num = num + str.charAt(i);
if (i==str.length()-1){ // check if it is last
sum = sum + Integer.parseInt(num);
}
} else {
if (!num.equals("")) {
sum = sum + Integer.parseInt(num);
num = "";
}
}
}
System.out.println(sum);
}
}
You can iterate on integer by using regex:
String str = "abc22gh20fg4";
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(str);
int sum = 0;
while (m.find()) {
sum += Integer.parseInt(m.group());
}
System.out.println(sum); // Output: 46
Append this line if character is digit
sum=sum+Integer.parseInt(num); one more time just after for loop
public static void main(String[] args) {
int totalIntegerValue=0;
String currentStringValue="";
String totalStringValue="";
Scanner s = new Scanner(System.in);
String input = s.nextLine();
for(int i=0; i<input.length(); i++) {
if(Character.isDigit(input.charAt(i))) {
currentStringValue+=input.charAt(i);
totalIntegerValue+=Integer.parseInt(currentStringValue);
totalStringValue+=currentStringValue+"+";
}
else
{
currentStringValue="";
}
}
System.out.println(totalStringValue.substring(0, totalStringValue.length()-1)+"="+totalIntegerValue);
s.close();
}

How to use regex to split a string containing numbers and letters in java

My task is splitting a string, which starts with numbers and contains numbers and letters, into two sub-strings.The first one consists of all numbers before the first letter. The second one is the remained part, and shouldn't be split even if it contains numbers.
For example, a string "123abc34de" should be split as: "123" and "abc34de".
I know how to write a regular expression for such a string, and it might look like this:
[0-9]{1,}[a-zA-Z]{1,}[a-zA-Z0-9]{0,}
I have tried multiple times but still don't know how to apply regex in String.split() method, and it seems very few online materials about this. Thanks for any help.
you can do it in this way
final String regex = "([0-9]{1,})([a-zA-Z]{1,}[a-zA-Z0-9]{0,})";
final String string = "123ahaha1234";
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}
matcher.group(1) contains the first part and matcher.group(2) contains the second
you can add it to a list/array using these values
You can use a pretty simple pattern : "^(\\d+)(\\w+)" which capture digits as start, and then when letters appear it take word-char
String string = "123abc34de";
Matcher matcher = Pattern.compile("^(\\d+)(\\w+)").matcher(string);
String firstpart = "";
String secondPart = "";
if (matcher.find()) {
firstpart = matcher.group(1);
secondPart = matcher.group(2);
}
System.out.println(firstpart + " - " + secondPart); // 123 - abc34de
This is not the correct way but u will get the result
public static void main(String[] args) {
String example = "1234abc123";
int index = 0;
String[] arr = new String[example.length()];
for (int i = 0; i < example.length(); i++) {
arr = example.split("");
try{
if(Integer.parseInt(arr[i]) >= 0 & Integer.parseInt(arr[i]) <= 9){
index = i;
}
else
break;
}catch (NumberFormatException e) {
index = index;
}
}
String firstHalf = example.substring(0,Integer.parseInt(arr[index])+1);
String secondHalf = example.substring(Integer.parseInt(arr[index])+1,example.length());
System.out.println(firstHalf);
System.out.println(secondHalf);
}
Output will be: 1234 and in next line abc123

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.

Finding second occurrence of a substring in a string in Java

We are given a string, say, "itiswhatitis" and a substring, say, "is".
I need to find the index of 'i' when the string "is" occurs a second time in the original string.
String.indexOf("is") will return 2 in this case. I want the output to be 10 in this case.
Use overloaded version of indexOf(), which takes the starting index (fromIndex) as 2nd parameter:
str.indexOf("is", str.indexOf("is") + 1);
I am using:
Apache Commons Lang: StringUtils.ordinalIndexOf()
StringUtils.ordinalIndexOf("Java Language", "a", 2)
int first = string.indexOf("is");
int second = string.indexOf("is", first + 1);
This overload starts looking for the substring from the given index.
You can write a function to return array of occurrence positions, Java has String.regionMatches function which is quite handy
public static ArrayList<Integer> occurrencesPos(String str, String substr) {
final boolean ignoreCase = true;
int substrLength = substr.length();
int strLength = str.length();
ArrayList<Integer> occurrenceArr = new ArrayList<Integer>();
for(int i = 0; i < strLength - substrLength + 1; i++) {
if(str.regionMatches(ignoreCase, i, substr, 0, substrLength)) {
occurrenceArr.add(i);
}
}
return occurrenceArr;
}
I hope I'm not late to the party.. Here is my answer. I like using Pattern/Matcher because it uses regex which should be more efficient. Yet, I think this answer could be enhanced:
Matcher matcher = Pattern.compile("is").matcher("I think there is a smarter solution, isn't there?");
int numOfOcurrences = 2;
for(int i = 0; i < numOfOcurrences; i++) matcher.find();
System.out.println("Index: " + matcher.start());
It seems to be a good party... I'm in:
public static int nthIndexOf(String str, String subStr, int count) {
int ind = -1;
while(count > 0) {
ind = str.indexOf(subStr, ind + 1);
if(ind == -1) return -1;
count--;
}
return ind;
}
i think a loop can be used.
1 - check if the last index of substring is not the end of the main string.
2 - take a new substring from the last index of the substring to the last index of the main string and check if it contains the search string
3 - repeat the steps in a loop
if you want to find index for more than 2 occurrence:
public static int ordinalIndexOf(String fullText,String subText,int pos){
if(fullText.contains(subText)){
if(pos <= 1){
return fullText.indexOf(subText);
}else{
--pos;
return fullText.indexOf(subText, ( ordinalIndexOf(fullText,subText,pos) + 1) );
}
}else{
return -1;
}
}
Anyone who is looking for Nth occurance of string
public class NthOccuranceExample {
public static void main(String[] args) {
String str1 = "helloworld good morning good evening good night";
String str2 = "ing";
int n = 2;
int index = nthOccurrence(str1, str2, n);
System.out.println("index of str2 in str1 at occurrence "+ n +" = "+ index);
}
public static int nthOccurrence(String str1, String str2, int n) {
String tempStr = str1;
int tempIndex = -1;
int finalIndex = 0;
for(int occurrence = 0; occurrence < n ; ++occurrence){
tempIndex = tempStr.indexOf(str2);
if(tempIndex==-1){
finalIndex = 0;
break;
}
tempStr = tempStr.substring(++tempIndex);
finalIndex+=tempIndex;
}
return --finalIndex;
}
}

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