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)
Related
I checked many discutions about the best way to concatenate many string In Java.
As i understood Stringbuilder is more efficient than the + operator.
Unfortunantly My question is a litlle bit different.
Given the string :"AAAAA", how can we concatenate it with n times the char '_',knowing that the '_' has to come before the String "AAAAA"
if n is equal to 3 and str="AAAAA", the result has to be the String "___AAAAA"
String str = "AAAAA";
for (int i=0;i<100;i++){
str="_"+str;
}
In my program i have a Longs String , so i have to use the efficient way.
Thank you
EDIT1:
As I have read some Solutions I discovered that I asked for Only One Case , SO I arrived to this Solution that i think is good:
public class Concatenation {
public static void main(String[] args) {
//so str is the String that i want to modify
StringBuilder str = new StringBuilder("AAAAA");
//As suggested
StringBuilder space = new StringBuilder();
for (int i = 0; i < 3; i++) {
space.append("_");
}
//another for loop to concatenate different char and not only the '_'
for (int i = 0; i < 3; i++) {
char next = getTheNewchar();
space.append(next);
}
space.append(str);
str = space;
System.out.println(str);
}
public static char getTheNewchar(){
//normally i return a rondom char, but for the case of simplicity i return the same char
return 'A';
}
}
Best way to concatenate Strings in Java: You don't.... Strings are immutable in Java. Each time you concatenate, you generate a new Object. Use StringBuilder instead.
StringBuilder sb = new StringBuilder();
for (int i=0;i<100;i++){
sb.append("_");
}
sb.append("AAAAA");
String str = sb.toString();
Go to char array, alloting the right size, fill the array, and sum it up back into a string.
Can’t beat that.
public String concat(char c, int l, String string) {
int sl = string.length();
char[] buf = new char[sl + l];
int pos = 0;
for (int i = 0; i < l; i++) {
buf[pos++] = c;
}
for (int i = 0; i < sl; i++) {
buf[pos++] = string.charAt(i);
}
return String.valueOf(buf);
}
I'd do something like:
import java.util.Arrays;
...
int numUnderbars = 3;
char[] underbarArray = new char[numUnderbars];
Arrays.fill(underbarArray, '_');
String output = String.valueOf(underbarArray) + "AAAA";
but the reality is that any of the solutions presented would likely be trivially different in run time.
If you do not like to write for loop use
org.apache.commons.lang.StringUtils class repeat(str,n) method.
Your code will be shorter:
String str=new StringBuilder(StringUtils.repeat("_",n)).append("AAAAA").toString();
BTW:
Actual answer to the question is in the code of that repeat method.
when 1 or 2 characters need to be repeated it uses char array in the loop, otherwise it uses StringBuilder append solution.
Lets say I have a string "aabbccaa". Now I want to replace occurrences of "aa" in given string by another string. But it should be in following way.
First occurrence of "aa" should be replaced by "1" and next occurrence of "aa" by "2" and so on.
So, the result of the string becomes "1bbcc2".
You can use replaceFirst() in a for loop where counter is incrementing...
for (int i = 1; string.contains("aa"); i++) {
string = string.replaceFirst("aa", "" + i);
}
You can do it using the Matcher's appendReplacement method:
Pattern p = Pattern.compile("aa");
Matcher m = p.matcher("aabbccaahhhaahhhaaahahhahaaakty");
StringBuffer sb = new StringBuffer();
// Variable "i" serves as a counter. It gets incremented after each replacement.
int i = 0;
while (m.find()) {
m.appendReplacement(sb, ""+(i++));
}
m.appendTail(sb);
System.out.println(sb.toString());
This approach lets you avoid creating multiple string objects (demo).
It is possible to do using Java functions but using a char array and doing it using a lower level of logic would be faster.
String s = "aabbccaa";
String target = "aa";
int i = 1;
String newS;
for (int j = 0; j < s.length; j++) {
newS = s.replaceFirst(target, i++);
j += newS.length - s.length;
s = newS;
}
Here is a solution :
public static void main(String[] a) {
int i = 1;
String before = "aabbccaabbaabbaa";
String regex = "aa";
String after = substitute(i, before, regex);
System.out.println(after);
}
private static String substitute(int i, String before, String regex) {
String after = before.replaceFirst(regex, Integer.toString(i++));
while (!before.equals(after)) {
before = after;
after = before.replaceFirst(regex, Integer.toString(i++));
}
return after;
}
Output :
1bbcc2bb3bb4
I have a problem: I need to find first occurrence of any symbol from string s2 (or array of char) in string s1.
Is there standard function for this purpose? If there isn't, whats the good implementation for this problem? (Of course I can run indexOf for every char from my s2, but this does't seem like a good algorithm, because if only the last symbol occurs in s1, we must run through s1 |s2|-1 times before I get an answer).
Thank you very much!
Put all characters from s2 into a constant-time lookup data structure (e.g. HashSet). Iterate over each character in s1 and see if your data structure contains that character.
Roughly (untested):
public int indexOfFirstContainedCharacter(String s1, String s2) {
Set<Character> set = new HashSet<Character>();
for (int i=0; i<s2.length; i++) {
set.add(s2.charAt(i)); // Build a constant-time lookup table.
}
for (int i=0; i<s1.length; i++) {
if (set.contains(s1.charAt(i)) {
return i; // Found a character in s1 also in s2.
}
}
return -1; // No matches.
}
This algorithm is O(n) as opposed to O(n^2) in the algorithm you describe.
Using regex:
public static void main(final String[] args) {
final String s1 = "Hello World";
final String s2 = "log";
final Pattern pattern = Pattern.compile("[" + Pattern.quote(s2) + "]");
final Matcher matcher = pattern.matcher(s1);
if (matcher.find()) {
System.out.println(matcher.group());
}
}
What you are looking for is indexOfAny from Apache StringUtils.
It looks like the implementation is:
public static int indexOfAny(String str, char[] searchChars) {
if (isEmpty(str) || ArrayUtils.isEmpty(searchChars)) {
return -1;
}
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
for (int j = 0; j < searchChars.length; j++) {
if (searchChars[j] == ch) {
return i;
}
}
}
return -1;
}
What is meant by symbol in this context? If it's just a 16-bit Java char, it's easy. Make a lookup table (array) for all possible values, indicating whether they appear in s2. Then step through s1 until either you've found a symbol from s2 or you've reached the end of s1. If a symbol is a Unicode code-point, it's more complicated, but the above gives a method to find out where you need to take a closer look.
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 );
I have a Java String object. I need to extract only digits from it. I'll give an example:
"123-456-789" I want "123456789"
Is there a library function that extracts only digits?
Thanks for the answers. Before I try these I need to know if I have to install any additional llibraries?
You can use regex and delete non-digits.
str = str.replaceAll("\\D+","");
Here's a more verbose solution. Less elegant, but probably faster:
public static String stripNonDigits(
final CharSequence input /* inspired by seh's comment */){
final StringBuilder sb = new StringBuilder(
input.length() /* also inspired by seh's comment */);
for(int i = 0; i < input.length(); i++){
final char c = input.charAt(i);
if(c > 47 && c < 58){
sb.append(c);
}
}
return sb.toString();
}
Test Code:
public static void main(final String[] args){
final String input = "0-123-abc-456-xyz-789";
final String result = stripNonDigits(input);
System.out.println(result);
}
Output:
0123456789
BTW: I did not use Character.isDigit(ch) because it accepts many other chars except 0 - 9.
public String extractDigits(String src) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < src.length(); i++) {
char c = src.charAt(i);
if (Character.isDigit(c)) {
builder.append(c);
}
}
return builder.toString();
}
Using Google Guava:
CharMatcher.inRange('0','9').retainFrom("123-456-789")
UPDATE:
Using Precomputed CharMatcher can further improve performance
CharMatcher ASCII_DIGITS=CharMatcher.inRange('0','9').precomputed();
ASCII_DIGITS.retainFrom("123-456-789");
input.replaceAll("[^0-9?!\\.]","")
This will ignore the decimal points.
eg: if you have an input as 445.3kg the output will be 445.3.
Using Google Guava:
CharMatcher.DIGIT.retainFrom("123-456-789");
CharMatcher is plug-able and quite interesting to use, for instance you can do the following:
String input = "My phone number is 123-456-789!";
String output = CharMatcher.is('-').or(CharMatcher.DIGIT).retainFrom(input);
output == 123-456-789
public class FindDigitFromString
{
public static void main(String[] args)
{
String s=" Hi How Are You 11 ";
String s1=s.replaceAll("[^0-9]+", "");
//*replacing all the value of string except digit by using "[^0-9]+" regex.*
System.out.println(s1);
}
}
Output: 11
Use regular expression to match your requirement.
String num,num1,num2;
String str = "123-456-789";
String regex ="(\\d+)";
Matcher matcher = Pattern.compile( regex ).matcher( str);
while (matcher.find( ))
{
num = matcher.group();
System.out.print(num);
}
I inspired by code Sean Patrick Floyd and little rewrite it for maximum performance i get.
public static String stripNonDigitsV2( CharSequence input ) {
if (input == null)
return null;
if ( input.length() == 0 )
return "";
char[] result = new char[input.length()];
int cursor = 0;
CharBuffer buffer = CharBuffer.wrap( input );
while ( buffer.hasRemaining() ) {
char chr = buffer.get();
if ( chr > 47 && chr < 58 )
result[cursor++] = chr;
}
return new String( result, 0, cursor );
}
i do Performance test to very long String with minimal numbers and result is:
Original code is 25,5% slower
Guava approach is 2.5-3 times slower
Regular expression with D+ is 3-3.5 times slower
Regular expression with only D is 25+ times slower
Btw it depends on how long that string is. With string that contains only 6 number is guava 50% slower and regexp 1 times slower
Using Kotlin and Lambda expressions you can do it like this:
val digitStr = str.filter { it.isDigit() }
You can use str.replaceAll("[^0-9]", "");
I have finalized the code for phone numbers +9 (987) 124124.
Unicode characters occupy 4 bytes.
public static String stripNonDigitsV2( CharSequence input ) {
if (input == null)
return null;
if ( input.length() == 0 )
return "";
char[] result = new char[input.length()];
int cursor = 0;
CharBuffer buffer = CharBuffer.wrap( input );
int i=0;
while ( i< buffer.length() ) { //buffer.hasRemaining()
char chr = buffer.get(i);
if (chr=='u'){
i=i+5;
chr=buffer.get(i);
}
if ( chr > 39 && chr < 58 )
result[cursor++] = chr;
i=i+1;
}
return new String( result, 0, cursor );
}
Code:
public class saasa {
public static void main(String[] args) {
// TODO Auto-generated method stub
String t="123-456-789";
t=t.replaceAll("-", "");
System.out.println(t);
}
import java.util.*;
public class FindDigits{
public static void main(String []args){
FindDigits h=new FindDigits();
h.checkStringIsNumerical();
}
void checkStringIsNumerical(){
String h="hello 123 for the rest of the 98475wt355";
for(int i=0;i<h.length();i++) {
if(h.charAt(i)!=' '){
System.out.println("Is this '"+h.charAt(i)+"' is a digit?:"+Character.isDigit(h.charAt(i)));
}
}
}
void checkStringIsNumerical2(){
String h="hello 123 for 2the rest of the 98475wt355";
for(int i=0;i<h.length();i++) {
char chr=h.charAt(i);
if(chr!=' '){
if(Character.isDigit(chr)){
System.out.print(chr) ;
}
}
}
}
}