在Java中有一种方法来检查条件:
"这个字符是否出现在字符串x中"
不使用循环?
在Java中有一种方法来检查条件:
"这个字符是否出现在字符串x中"
不使用循环?
当前回答
如果你在JAVA中看到indexOf的源代码:
public int indexOf(int ch, int fromIndex) {
final int max = value.length;
if (fromIndex < 0) {
fromIndex = 0;
} else if (fromIndex >= max) {
// Note: fromIndex might be near -1>>>1.
return -1;
}
if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
// handle most cases here (ch is a BMP code point or a
// negative value (invalid code point))
final char[] value = this.value;
for (int i = fromIndex; i < max; i++) {
if (value[i] == ch) {
return i;
}
}
return -1;
} else {
return indexOfSupplementary(ch, fromIndex);
}
}
你可以看到它使用for循环来查找字符。注意,在代码中使用的每个indexOf都等于一个循环。
因此,对于单个字符使用循环是不可避免的。
但是,如果您想找到具有更多不同形式的特殊字符串,请使用有用的库,如util。regex,它部署了更强的算法来匹配字符或字符串模式与正则表达式。例如,在字符串中查找电子邮件:
String regex = "^(.+)@(.+)$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(email);
如果你不喜欢使用正则表达式,只需使用循环和charAt,并尝试在一个循环中覆盖所有情况。
注意递归方法比循环方法有更多的开销,所以不推荐使用。
其他回答
你可以使用string.indexOf('a')。
如果字符a出现在string中:
它返回中字符第一次出现的索引 对象表示的字符序列,或-1 性格不会出现。
如果你在JAVA中看到indexOf的源代码:
public int indexOf(int ch, int fromIndex) {
final int max = value.length;
if (fromIndex < 0) {
fromIndex = 0;
} else if (fromIndex >= max) {
// Note: fromIndex might be near -1>>>1.
return -1;
}
if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
// handle most cases here (ch is a BMP code point or a
// negative value (invalid code point))
final char[] value = this.value;
for (int i = fromIndex; i < max; i++) {
if (value[i] == ch) {
return i;
}
}
return -1;
} else {
return indexOfSupplementary(ch, fromIndex);
}
}
你可以看到它使用for循环来查找字符。注意,在代码中使用的每个indexOf都等于一个循环。
因此,对于单个字符使用循环是不可避免的。
但是,如果您想找到具有更多不同形式的特殊字符串,请使用有用的库,如util。regex,它部署了更强的算法来匹配字符或字符串模式与正则表达式。例如,在字符串中查找电子邮件:
String regex = "^(.+)@(.+)$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(email);
如果你不喜欢使用正则表达式,只需使用循环和charAt,并尝试在一个循环中覆盖所有情况。
注意递归方法比循环方法有更多的开销,所以不推荐使用。
您可以使用String类中的两个方法。
string .contains()检查字符串是否包含指定的char值序列 string . indexof()返回字符串中第一次出现指定字符或子字符串的索引,如果没有找到该字符则返回-1(此方法有4种变体)
方法1:
String myString = "foobar";
if (myString.contains("x") {
// Do something.
}
方法2:
String myString = "foobar";
if (myString.indexOf("x") >= 0 {
// Do something.
}
链接作者:Zach Scrivena
如果有人用这个;
let text = "Hello world, welcome to the universe.";
let result = text.includes("world");
console.log(result) ....// true
结果将是true或false
这对我来说总是有效的
static String removeOccurences(String a, String b)
{
StringBuilder s2 = new StringBuilder(a);
for(int i=0;i<b.length();i++){
char ch = b.charAt(i);
System.out.println(ch+" first index"+a.indexOf(ch));
int lastind = a.lastIndexOf(ch);
for(int k=new String(s2).indexOf(ch);k > 0;k=new String(s2).indexOf(ch)){
if(s2.charAt(k) == ch){
s2.deleteCharAt(k);
System.out.println("val of s2 : "+s2.toString());
}
}
}
System.out.println(s1.toString());
return (s1.toString());
}