gpt4 book ai didi

java - 在字符串中搜索并获取相等的字符

转载 作者:行者123 更新时间:2023-12-01 19:41:59 25 4
gpt4 key购买 nike

我需要在另一个字符串中逐个字符搜索某个字符串,如果字符相同则得到这样的字符;

我就是这样做的

public String searchForSignature(String texto2) throws NoSuchAlgorithmException {
String myString = "", foundString = "";
myString = "aeiousrtmvb257";
for (int i = 0; i < texto2.length() || i <= 1000; i++) {
char c = texto2.charAt(i);

for (int j = 0; j < myString.length(); j++) {
if (c == myString.charAt(j)) {
foundString = foundString + c;
}
}
}
return foundString;
}

我想提高性能,看到有表格和使用正则表达式,因为我还是一个外行,所以我无法按照我的方式成功。

 public String searchForSignature2(String texto2) {
Pattern pattern = Pattern.compile("aeiousrtmvb257");
Matcher matcher = pattern.matcher(texto2);
while (matcher.find()) {
System.out.println(matcher.group(1));
}
return matcher.group(1).toString();
}

不返回任何内容

//编辑

说实话,我想我对这个问题不是很清楚。实际上我需要获取字符串中等于“aeiousrtmvb257”的所有字符

我就是这么做的,现在看来还可以,只是不知道性能是否令人满意。

 public String searchForSignature2(String texto2) {
String foundString = "";
Pattern pattern = Pattern.compile("[aeiousrtmvb257]");
Matcher matcher = pattern.matcher(texto2);
while (matcher.find()) {
System.out.println(matcher.group());
foundString+=matcher.group();
}
return foundString;
}
}

最佳答案

据我理解你的问题,通过使用 PatternMatcher 这应该可以解决问题:

代码

private static final String PATTERN_TO_FIND = "[aeiousrtmvb257]";

public static void main(String[] args) {
System.out.println(searchForSignature2("111aeiousrtmvb257111"));
}

public static String searchForSignature2(String texto2) {
Pattern pattern = Pattern.compile(PATTERN_TO_FIND);
Matcher matcher = pattern.matcher(texto2);

StringBuilder result = new StringBuilder();

while (matcher.find()) {
result.append(matcher.group());
}

return result.toString();
}

输出

aeiousrtmvb257

关于java - 在字符串中搜索并获取相等的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55065467/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com