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.
Related
I have to write a method which breaks a string into groups. The user should give the amount of letters per group and the function should return a string that consists of the input string broken into groups. For instance, function(“HELLOYOU”, 2) would return “HE LL OY OU”.
You can use String.split() to break the string into an array of individual letters, and then combine pairs of letters, or larger groups, etc.
Here is some example code:
String[] splitInParts(String input, int size) {
String[] letters = input.split("");
String[] output = new String[letters / size];
for (int i = 0; i < output.length; i++) {
output[i] = "";
for (int j = 0; j < size; j++) {
output[i] = output[i] + letters[size * i + j];
}
}
return output;
}
There is a lot of boilerplate code missing, for example, checking that loop parameters are in range, checking strings are not null, etc. However this is a rough idea of how you could go about doing it.
You can move the characters of input String to a new String and put whitespaces on every step that equals to "size":
String function(String input, int parts) {
StringBuilder result = new StringBuilder();
int partCounter = 0;
for (int i = 0; i < input.length(); i++) {
partCounter++;
result.append(input.charAt(i));
if (partCounter == parts){
result.append(" ");
partCounter = 0;
}
}
return result.toString();
}
You could use the below code that takes in a String instance and aN int defining the number of characters to split based on. And then use the String instances split method.
public static String[] split(String input, int len){
// To prevent any NullPointerException being thrown
if (StringUtils.isEmpty()) {
return null;
}
// Split the input string based on a regex pattern
return input.split(String.format("(?<=\\G.{%1$d})", len));
}
The Regular Expression that is being used here is (?<=\\G.{%1$d}) which based on len being 2 would become (?<=\\G.{2}). So this means it would split every 2 characters. So the output for a string of HELLOWORLD would be HE, LL, OW, OR, LD .
If you wanted to join those into one String separated by a space you could using the StringUtils#join method.
String joinedString = StringUtils.join(split, StringUtils.SPACE);
Which would produce "HE LL OW OR LD".
So an all in one method would be:
public static String separateNthCharacter(String input, int len) {
// To prevent any NullPointerException being thrown
if (StringUtils.isEmpty()) {
return StringUtils.EMPTY;
}
String[] split = input.split(String.format("(?<=\\G.{%1$d})", len));
return StringUtils.join(split, StringUtils.SPACE);
}
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)
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;
}
I am needed find number of mismatching characters between two strings. Currently i m doing it by converting strings into char Arrays and comparing element by element.
Is there any other way to achieve above requirement.
Note: consider string as lower case
Inputs :
input
utput
Output :
2
StringUtils in Apache commons.lang has a method for getting the Levenshtein distance of two strings.
If the two string are of different size the following code you return the total mismatch of alphabets.
You can try this -
String ip1 = "input"; // input1
String ip2 = "utput"; // input2
int count = 0; // difference in string
String ipx2 = ip2;
for (int j = 0; j <= ip2.length(); j++) {
int value = ip1.indexOf(ipx2);
if (value != -1) {
if (("").equals(ipx2)) { // if the second string is blank after continous reducing
count = ip1.length() + ip2.length();
} else {
count = ip1.length() + ip2.length() - 2 * ipx2.length();
}
break;
} else {
count = ip1.length() + ip2.length(); // if there is no match at all
}
ipx2 = ip2.substring(j);
}
System.out.println("" + count);
}
You will have to check whether the inputs have some data or not. I have not done that check.
This is the way you are describing, but it is the simplest way of implementing:
int counter = 0;
for(int i = 0; i < str1.length(); i++) if(str1.charAt(i) != str2.charAt(i)) counter++;
They can be fit on just two lines of code, without explicitly creating a whole new character array.
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 );