2011-10-04 141 views
1

我想检查某些字符的字符串。这些角色基本上都在列表中。但是,我不知道如何实现这一点。我唯一的想法是遍历字符串,检查每个字符的字符串的第一个字符。例如,如果我的字符串是:“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. 
+1

正则表达式就是为此设计的。 [ldefhp] – Joe

+0

你也可以检查每个字母的新字符串.indexOf() – yoozer8

+0

我不想处理正则表达式,对不起:)。我根本不认识他们。 –

回答

0

j应该是比较可能它已经设置为true后要设置isStringfalse的的newString
长度。

+0

我相信布尔表达式是正确的。尽管它最初设置为false,但它只是初始化布尔表达式。之后,我可以随时将其更改为真假。 –

+0

@Macosx Iam - 返回的isString是将数组中最后一个字符与字符串中最后一个字符进行比较的结果。 –

+0

是的,我希望字符数组遍历并检查字符串中的每个索引。我会在代码顶部旁边提供一个更清晰的示例。 –

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;