我正在尝试检查某些字符的字符串。字符基本上在列表中。但是,我不知道如何实现这一目标。我唯一的想法是遍历字符串,检查字符串的第一个字符对每个字符。例如,如果我的字符串是:“ablacablada”,我要检查的字符是(l,d,e,f,h,p),我会检查“ablacablada”字符串中的索引0。我会遍历字符列表,看看索引0处的字符是否为“l”。如果没有,我会继续索引1,依此类推。这是我的代码:
public boolean stringChecker()
{
String newString = "ablacablada";
char [] newChar = {l; d; e; f; h; p};
String charString = new String(newChar)
boolean isString = false;
for (int i=0; i<charString.length(); i++)
{
for (int j=0; j<newString; j++)
{
if(charString.charAt(i) == newString.charAt(j))
{
isString = true; // a character in the list (l, d, e, f, h, p) is detected
}
else
{
isString = false;
}
}
}
return isString;
}
这是我的想法。但是,它不起作用。如果有人能指出我正确的方向,我将不胜感激。提前谢谢。
P.S。这就是我的意思:
"a b l a c a b l a d a"
1. check the a from the character list.
Is "a" == "l"? No.
Is "a" == "d"? No.
Is "a" == "e"? No.
Is "a" == "f"? No.
Is "a" == "h"? No.
Is "a" == "p"? No.
2. Move on to index 1.
Is "b" == "l"? No.
Is "b" == "d"? No.
Is "b" == "d"? No...
And so on.
答案 0 :(得分:0)
j
应与newString
的长度进行比较
您可能已将isString
设置为false
,然后将其设置为true
。
答案 1 :(得分:0)
以下是使用正则表达式的示例:
Pattern p = Pattern.compile("[ldefhp]");
// Split input with the pattern
Matcher m = p.matcher("asdnbllksksksdf");
boolean result = m.find();
System.out.println(result); // true
<小时/> 编辑没有正则表达式。找到针后返回/退出:
String newString = "ablacablada";
char [] newChar = {l; d; e; f; h; p};
String charString = new String(newChar)
boolean isString = false;
for (int i=0; i<charString.length(); i++)
{
for (int j=0; j<newString; j++)
{
if(charString.charAt(i) == newString.charAt(j))
{
return true; // a character in the list (l, d, e, f, h, p) is detected
}
}
}
return false;