[英]Find count of digits in string variable
我有一個字符串,有時給出字符值,有時給出整數值。 我想獲得該字符串中的位數。
例如,如果字符串包含“2485083572085748”,則總位數為 16。
請幫我解決一下這個。
使用正則表達式的更清潔的解決方案:
// 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++;
}
}
只是為了使用計算字符串中數字的流選項刷新此線程:
"2485083572085748".chars()
.filter(Character::isDigit)
.count();
如果您的字符串變得很大並且充滿了數字以外的其他內容,您應該嘗試使用正則表達式來完成。 下面的代碼會對你這樣做:
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++;
}
查看java regex 課程了解更多信息。 干杯!
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;
}
循環每個字符並計算它。
String s = "2485083572085748";
int counter = 0;
for(char c : s.toCharArray()) {
if( c >= '0' && c<= '9') {
++counter;
}
}
System.out.println(counter);
在 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
謝謝 --> https://stackoverflow.com/users/1396264/vedant對於上面的 Java 版本。 它也幫助了我。
就像是:
using System.Text.RegularExpressions;
Regex r = new Regex( "[0-9]" );
Console.WriteLine( "Matches " + r.Matches("if string contains 2485083572085748 then" ).Count );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.