【发布时间】:2012-11-06 06:20:51
【问题描述】:
我们如何检查包含任何字符的任何字符串,时间如何...... 例子: engineering 是一个字符串,包含多少次 'g' 在完整的字符串中
【问题讨论】:
-
将其转换为字符数组并循环检查匹配项。查看java.util.String
标签: java
我们如何检查包含任何字符的任何字符串,时间如何...... 例子: engineering 是一个字符串,包含多少次 'g' 在完整的字符串中
【问题讨论】:
标签: java
我知道这是个老问题,但有一个选项没有得到回答,而且很简单:
int count = string.length() - string.replaceAll("g","").length()
【讨论】:
试试这个
int count = StringUtils.countMatches("engineering", "e");
更多关于StringUtils可以从问题中了解到:How do I use StringUtils in Java?
【讨论】:
StringUtils?
你可以试试 Java-8 的方式。简单、简单且更具可读性。
long countOfA = str.chars().filter(ch -> ch == 'g').count();
【讨论】:
使用正则表达式[g] 查找字符并计算结果如下:
Pattern pattern = Pattern.compile("[g]");
Matcher matcher = pattern.matcher("engineering");
int countCharacter = 0;
while(matcher.find()) {
countCharacter++;
}
System.out.println(countCharacter);
如果您想要不区分大小写的计数,请在 Pattern 中使用正则表达式作为 [gG]。
【讨论】:
使用 org.apache.commons.lang3 包来使用 StringUtils 类。 下载 jar 文件并将其放入 Web 应用程序的 lib 文件夹中。
int count = StringUtils.countMatches("engineering", "e");
【讨论】:
虽然 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:-
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == toCheck) {
count++;
}
}
【讨论】:
3 作为计数。
我会使用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++;
【讨论】:
String s = "engineering";
char c = 'g';
s.replaceAll("[^"+ c +"]", "").length();
【讨论】:
char c 来自用户输入,则这种方法容易受到正则表达式注入的影响。 (类似于SQL注入)
这是一个非常古老的问题,但这可能会帮助某人(“_”)
你可以简单地使用这个代码
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;
}
【讨论】:
您可以尝试以下操作:
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 编写的,但我会用 Python 回答它。这可能会有所帮助:
string = 'E75;Z;00001;'
a = string.split(';')
print(len(a)-1)
【讨论】: