[英]check how many times string contains character 'g' in eligible string
我們怎樣才能檢查包含任何字符如何可以任何時間字符串....例如: 工程是一個字符串包含多少次完整的字符串“G”
我知道這是一個古老的問題,但是有一個選項沒有得到回答,這很簡單:
int count = string.length() - string.replaceAll("g","").length()
嘗試這個
int count = StringUtils.countMatches("engineering", "e");
有關StringUtils的更多信息可以從以下問題中了解到: 如何在Java中使用StringUtils?
我會使用Pattern
和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++;
盡管Regex可以正常工作,但是在這里並不需要。 您可以簡單地使用for-loop
來維護字符count
。
您需要將字符串轉換為char數組:-
String str = "engineering";
char toCheck = 'g';
int count = 0;
for (char ch: str.toCharArray()) {
if (ch == toCheck) {
count++;
}
}
System.out.println(count);
或者,您也可以不轉換為charArray
來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();
使用正則表達式[g]
查找字符並計算發現結果,如下所示:
Pattern pattern = Pattern.compile("[g]");
Matcher matcher = pattern.matcher("engineering");
int countCharacter = 0;
while(matcher.find()) {
countCharacter++;
}
System.out.println(countCharacter);
如果需要不區分大小寫的計數,請在模式中將正則表達式用作[gG]
。
使用org.apache.commons.lang3包來使用StringUtils類。 下載jar文件並將其放入Web應用程序的lib文件夾中。
int count = StringUtils.countMatches("engineering", "e");
這是一個非常老的問題,但這可能會對某人有所幫助(“ _”)
您可以只使用此代碼
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 = getCountOf(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;
}
您可以嘗試以下操作:
String str = "engineering";
int letterCount = 0;
int index = -1;
while((index = str.indexOf('g', index+1)) > 0)
letterCount++;
System.out.println("Letter Count = " + letterCount);
您可以遍歷它,並保留想要的字母數。
public class Program {
public static int countAChars(String s) {
int count = 0;
for(char c : s.toCharArray()) {
if('a' == c) {
count++;
}
}
return count;
}
}
或者您可以使用StringUtils進行計數。
int count = StringUtils.countMatches("engineering", "e");
您可以嘗試Java-8方式。 簡單,簡單且可讀性強。
long countOfA = str.chars().filter(ch -> ch == 'g').count();
這是一個古老的問題,它在Java中,但我將在Python中回答。 這可能會有所幫助:
string = 'E75;Z;00001;'
a = string.split(';')
print(len(a)-1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.