Java 如何检查单个字符是否出现在字符串中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/506105/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I check if a single character appears in a string?
提问by barfoon
In Java is there a way to check the condition:
在 Java 中有一种方法可以检查条件:
"Does this single character appear at all in string x"
“这个单个字符是否出现在字符串 x 中”
withoutusing a loop?
不使用循环?
采纳答案by mP.
You can use string.indexOf('a')
.
您可以使用string.indexOf('a')
.
If the char a
is present in string
:
如果字符a
存在于string
:
it returns the the index of the first occurrence of the character in the character sequence represented by this object, or -1 if the character does not occur.
它返回此对象表示的字符序列中该字符第一次出现的索引,如果该字符没有出现,则返回 -1。
回答by Zach Scrivena
String.contains()
which checks if the string contains a specified sequence of char valuesString.indexOf()
which returns the index within the string of the first occurence of the specified character or substring (there are 4 variations of this method)
String.contains()
它检查字符串是否包含指定的字符值序列String.indexOf()
它返回指定字符或子字符串第一次出现的字符串中的索引(此方法有 4 种变体)
回答by mweiss
To check if something does not exist in a string, you at least need to look at each character in a string. So even if you don't explicitly use a loop, it'll have the same efficiency. That being said, you can try using str.contains(""+char).
要检查字符串中是否不存在某些内容,您至少需要查看字符串中的每个字符。因此,即使您没有明确使用循环,它也会具有相同的效率。话虽如此,您可以尝试使用 str.contains(""+char)。
回答by Mystic
Yes, using the indexOf() method on the string class. See the API documentation for this method
是的,在字符串类上使用 indexOf() 方法。请参阅此方法的 API 文档
回答by Hyman Leow
I'm not sure what the original poster is asking exactly. Since indexOf(...) and contains(...) both probablyuse loops internally, perhaps he's looking to see if this is possible at all without a loop? I can think of two ways off hand, one would of course be recurrsion:
我不确定原始海报究竟在问什么。由于 indexOf(...) 和 contains(...) 都可能在内部使用循环,也许他想看看这是否可能没有循环?我可以想到两种方法,一种当然是递归:
public boolean containsChar(String s, char search) {
if (s.length() == 0)
return false;
else
return s.charAt(0) == search || containsChar(s.substring(1), search);
}
The other is far less elegant, but completeness...:
另一个远不那么优雅,但完整性......:
/**
* Works for strings of up to 5 characters
*/
public boolean containsChar(String s, char search) {
if (s.length() > 5) throw IllegalArgumentException();
try {
if (s.charAt(0) == search) return true;
if (s.charAt(1) == search) return true;
if (s.charAt(2) == search) return true;
if (s.charAt(3) == search) return true;
if (s.charAt(4) == search) return true;
} catch (IndexOutOfBoundsException e) {
// this should never happen...
return false;
}
return false;
}
The number of lines grow as you need to support longer and longer strings of course. But there are no loops/recurrsions at all. You can even remove the length check if you're concerned that that length() uses a loop.
当然,随着您需要支持越来越长的字符串,行数会增加。但是根本没有循环/递归。如果您担心 length() 使用循环,您甚至可以删除长度检查。
回答by Richard
String temp = "abcdefghi";
if(temp.indexOf("b")!=-1)
{
System.out.println("there is 'b' in temp string");
}
else
{
System.out.println("there is no 'b' in temp string");
}
回答by praveen
String s="praveen";
boolean p=s.contains("s");
if(p)
System.out.println("string contains the char 's'");
else
System.out.println("string does not contains the char 's'");
Output
输出
string does not contains the char 's'
回答by anytime
//this is only the main... you can use wither buffered reader or scanner
//这只是主要的...你可以使用枯萎的缓冲阅读器或扫描仪
string s;
int l=s.length();
int f=0;
for(int i=0;i<l;i++)
{
char ch1=s.charAt(i);
for(int j=0;j<l;j++)
{
char ch2=charAt(j);
if(ch1==ch2)
{
f=f+1;
s.replace(ch2,'');
}
f=0;
}
}
//if replacing with null does not work then make it space by using ' ' and add a if condition on top.. checking if its space if not then only perform the inner loop...
回答by fillumina
If you need to check the same string often you can calculate the character occurrences up-front. This is an implementation that uses a bit array contained into a long array:
如果您需要经常检查相同的字符串,您可以预先计算字符出现次数。这是一个使用包含在长数组中的位数组的实现:
public class FastCharacterInStringChecker implements Serializable {
private static final long serialVersionUID = 1L;
private final long[] l = new long[1024]; // 65536 / 64 = 1024
public FastCharacterInStringChecker(final String string) {
for (final char c: string.toCharArray()) {
final int index = c >> 6;
final int value = c - (index << 6);
l[index] |= 1L << value;
}
}
public boolean contains(final char c) {
final int index = c >> 6; // c / 64
final int value = c - (index << 6); // c - (index * 64)
return (l[index] & (1L << value)) != 0;
}}
回答by Ganeshmani
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());
}