2013-05-13 22 views
2
的阵列

所以我有以下字符串:狗“和”猫 我把它分解成一个数组名为:数组1带,仰望引号用绳子

{“d”,“O”, 'G',””, '“', 'C', 'A',T”, '”'}

boolean works = false; 

for (int i=0; i < array1.length;i++){ 

    if (array1[i].equals("d"){ 
     if (array1[i+1].equals("o"){ 
      if(array1[i+2].equals("g"){ 
       if (array1[i+3].equals(" "){ 
        if (array1[i+4].equals("""){ //does work here 
        if (array1[i+5].equals("c"){ 
         if (array1[i+6].equals("a"){ 
          if (array1[i+7].equals("t"){ 
          works = true; 
          } 
         } 
        } 
        } 
       } 
      } 
     } 
    } 
} 

System.out.println(works); 

它在与报价等号不工作。有没有人有任何想法?

+7

逃脱字符。请不要做这样的事情。 – 2013-05-13 16:25:00

+3

使用反斜杠:“\”“' – 2013-05-13 16:25:21

+0

http://en.wikipedia.org/wiki/String_searching_algorithm#Single_pattern_algorithms – SLaks 2013-05-13 16:54:25

回答

2

我会尽量简化你的代码,例如,你可以写

String s = "dog \"and\" cat"; 
boolean works = s.contains("dog \"cat"); 

这使得它更明显的是,工作永远是假的。

0

你有不明确的数据类型。

我假定您的array1char[]类型。如果是,那么你应该有==比较在你的代码(注意单引号“X”,其中x是要测试的字符):

if (array1[i] == 'd'){ 
    .... 
} 

如果数组是String[]类型,那么你需要逃避“字符在比较中使用反斜杠:

if (array1[i+4].equals("\""){ //does work here 
    .... 
} 
0

您需要转义”内的字符“。就像这样:

(array1[i+4].equals("\"") 
0

{'d','o','g',' ','"','c','a',t','"'}这是一个字符数组 你需要下面的代码 您不能等于Char相字符串。

boolean works = false; 
for (int i=0; i < array1.length;i++){ 
if (array1[i]=='d'){ 
    if (array1[i+1]=='o'){ 
     if(array1[i+2]=='g'){ 
      if (array1[i+3]==' '){ 
       if (array1[i+4]=='"'){ //does work here 
       if (array1[i+5]=='c'){ 
        if (array1[i+6]=='a'){ 
         if (array1[i+7]=='t'){ 
         works = true;` 
         } 
        } 
       } 
       } 
      } 
     } 
    } 
} 
0
boolean works = false; 
String[] pattern = { "d","o","g"," ","\"","c","a","t","\"" }; 

for (int i = 0; i < array1.length; i++) { 
    // Loop over the items in the pattern array, and check if they match array1 
    boolean inner = true; 
    for (int j = 0; j < pattern.length; j++) { 
     if (i + j >= array1.length) { 
      // Don't go beyond the end of array1 
      break; 
     } 
     if (!pattern[j].equals(array1[i+j])) { 
      // We found an item that doesn't match. 
      inner = false; 
      break; 
     } 
    } 
    if (inner) { 
     // All items matched 
     works = true; 
     break; 
    } 
} 

System.out.println(works);