我需要在另一个逐个字符的字符串中搜索某个字符串,如果两个字符相同,则获取该字符;
我正在这样做
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;
}
}
答案 0 :(得分:1)
据我所知,您可以使用Pattern
和Matcher
来解决问题:
代码
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
答案 1 :(得分:1)
我不知道texto2.length() || i <= 1000
背后的原因是什么,但是基于您方法中的逻辑,我可以建议以下解决方案:
public static void main(String... args) throws IOException {
System.out.println(searchForSignature("hello"));
}
public static String searchForSignature(String texto2) {
String myString = "aeiousrtmvb257";
StringBuilder builder = new StringBuilder();
for (char s : texto2.toCharArray()) {
if (myString.indexOf(s) != -1) {
builder.append(s);
}
}
return builder.toString();
}
输出:eo
答案 2 :(得分:1)
我不明白,为什么要打印找到的字符串
public static String searchForSignature2(String texto2) {
String maaString = "aeiousrtmvb257";
String toSearch = ".*" + maaString +".*";
boolean b = Pattern.matches(toSearch, texto2);
return b ? maaString : "";
}
public static void main(String[] args)
{
String input = "4erdhrAW BLBAJJINJOI WETSEKMsef saemfosnens3bntu is5o3n029j29i30kwq23eki4"+
"maoifmakakmkakmsmfajiwfuanyi gaeniygaenigaenigeanige anigeanjeagjnageunega"+
"movmmklmklzvxmkxzcvmoifsadoi asfugufngs"+
"wpawfmaopfwamopfwampfwampofwampfawmfwamokfesomk"+
"3rwq3rqrq3rqetgwtgwaeiousrtmvb2576266wdgdgdgdgd";
String myString = searchForSignature2(input);
System.out.println(myString);
}
您需要添加。*来表明您的字符串被任何字符包围