在Java中有一种方法来检查条件:
"这个字符是否出现在字符串x中"
不使用循环?
在Java中有一种方法来检查条件:
"这个字符是否出现在字符串x中"
不使用循环?
当前回答
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());
}
其他回答
如果有人用这个;
let text = "Hello world, welcome to the universe.";
let result = text.includes("world");
console.log(result) ....// true
结果将是true或false
这对我来说总是有效的
你可以使用string.indexOf('a')。
如果字符a出现在string中:
它返回中字符第一次出现的索引 对象表示的字符序列,或-1 性格不会出现。
package com;
public class _index {
public static void main(String[] args) {
String s1="be proud to be an indian";
char ch=s1.charAt(s1.indexOf('e'));
int count = 0;
for(int i=0;i<s1.length();i++) {
if(s1.charAt(i)=='e'){
System.out.println("number of E:=="+ch);
count++;
}
}
System.out.println("Total count of E:=="+count);
}
}
如果不使用循环/递归至少检查一次字符串,您将无法检查char是否出现在某些字符串中(像indexOf这样的内置方法也使用循环)
如果不是。如果你在字符串中查找一个字符,x比字符串的长度要多得多,我建议使用Set数据结构,因为这比简单地使用indexOf更有效
String s = "abc";
// Build a set so we can check if character exists in constant time O(1)
Set<Character> set = new HashSet<>();
int len = s.length();
for(int i = 0; i < len; i++) set.add(s.charAt(i));
// Now we can check without the need of a loop
// contains method of set doesn't use a loop unlike string's contains method
set.contains('a') // true
set.contains('z') // false
使用set,你将能够在常数时间O(1)检查字符是否存在于字符串中,但你也将使用额外的内存(空间复杂度将是O(n))。
是的,在字符串类上使用indexOf()方法。请参阅此方法的API文档