2014-11-16 27 views
0

程序检查字符串中的第一个字符是否是标点符号,如果是,则删除该字符并返回新字。检查字符是否为标点符号

public static String checkStart(String word){ 
    char [] punctuation = {'.' , ',' , ';' , ':', '?' , '!' , '"' , '\'' , ')' , '('}; 
    int i; 

    for (i = 0; i < punctuation.length;i++){ 
     if(word.charAt(0) == punctuation[i]){ 
      word = word.substring(1); 
     }  
    } 
    return word; 
} 

为什么不起作用?

这里是方法调用者

public static String[] removePunctuation(String [] words){ 
    int i, j; 

    for (i = 0; i < words.length;i++){ 
     words[i] = checkStart(words[i]); 
    } 
    return words; 
} 

}

+1

看到你的标点符号数组的问题是与此。 – sumanta

+0

什么是不工作?你有错误吗? – furkle

+0

该程序将运行,但它会给出NullPointerException异常 并且它不会删除第一个字符,adasd仍将是asdasd – newbie

回答

1

为我工作。

public static void main(String[] args) { 
    System.out.println(checkStart(",abcd")); 
} 

输出:

abcd 

你可能在你主要方法的错误。

0

我把你的代码放到我的NetBeans和它似乎运行正常:

public class Test{ 
    public static String checkStart(String word){ 
     char [] punctuation = {'.' , ',' , ';' , ':', '?' , '!' , '"' , '\'' , ')' , '('}; 
     int i; 

     for (i = 0; i < punctuation.length;i++){ 
      if(word.charAt(0) == punctuation[i]){ 
       word = word.substring(1); 
      }  
     } 
     return word; 
    } 

    public static void main(String args[]){ 
     System.out.println(checkStart("test")); 
     System.out.println(checkStart("!test")); 
     System.out.println(checkStart(";test")); 
     System.out.println(checkStart("(test")); 
    } 
} 

这不得不输出:

测试

测试

测试

测试

0

我不完全清楚,但我想你想在一些特定字符后得到字符串。 所以我改变了下面的代码。

package org.owls.test; 

public class CheckStart { 
    private static String checkStart(String word){ 
     char [] punctuation = {'.' , ',' , ';' , ':', '?' , '!' , '"' , '\'' , ')' , '('}; 
     int i; 

     for (i = 0; i < punctuation.length;i++){ 
      for(int j = 0; j < word.length(); j++){ 
       if(word.charAt(j) == punctuation[i]){ 
        word = word.substring(j); 
       }  
      } 
     } 
     return word; 
    } 

    public static void main(String[] args) { 
     System.out.println(checkStart("gasf;dgjHJK")); 
    } 
} 

所以你可以得到'; dgjHJK'作为回报​​。如果有多个关键字,并且只想从第一个开始子串,则在checkStart中将break;添加到第二个循环。

祝您有美好的一天!检查

+0

您在子串参数中将'j'更改为'j + 1' –

1

计划,如果字符串中的第一个字符是一个标点符号

这其实并不完全做到这一点。想想如果你输入“。,; Hello”会发生什么 - 在这种情况下,你会回到“你好”。另一方面,如果您输入“;,。Hello”,您将返回“,.Hello” - 这是因为您按顺序遍历数组,并且在第一种情况下,标点按照正确的顺序排列每个符号都要被捕获,但在第二种情况下,当您查看标点符号[0]或标点符号[1]时,逗号和句号都不是零。我不确定这些行为之一是否是你发现的错误,但我认为其中至少有一个是不正确的。