2015-11-06 156 views
1

我是java的初学者,在将它从用户获取并将其作为单词返回之前从标记中删除所有标点符号时,我需要帮助将单词转换为小写。标点符号是指不是字母或连字符的任何内容。请注意,标点符号可以出现在字母之前和之后(例如,这是“一个示例,它显示了这种情况)。在这个例子中,它应该返回单词this,is,an,example,which,show,this,occurrence。谢谢!在java中删除标点符号

+1

你必须付出一些努力。通过编辑您的问题发布您已编写的代码以解决此问题。 StackOverflow不是代码写入服务。此外,还有标准的Java函数来使字符串小写。请阅读[Java String文档](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html) – Arc676

+0

我知道如何从用户获得输入的基本使用扫描仪并将其转换为小写,但我不知道如何去除所有标点符号。 – Smith

+0

尝试阅读正则表达式以及如何在Java中使用它们。 – Arc676

回答

0

要小写

string.toLowerCase() 

您可以使用正则表达式用空格

免责声明更换所有的标点字符:此代码使用Perl,并更换空间破折号测试,而不是Java替代标点符号与空间(所以技术上它没有经过测试)。但是,根据this site\p{Punct}应匹配所有标点符号。

Pattern p = Pattern.compile("\p{Punct}"); 
Matcher m = p.matcher(string); 
string = m.replaceAll(" "); 
String words[] = string.split(" "); //if you need it 
0

删除字符是简单的使用replaceAll。您只需编写一个适合您需求的正则表达式。

public class Main { 

    public static void main(String[] args) throws Exception { 
     String sentence = "Hi! I'm a sentence with (some) Punctuation."; 
     String reduced = sentence.toLowerCase().replaceAll("[^\\s\\w]", ""); 
     System.out.println(reduced); 
    } 
} 

这打印hi im a sentence with some punctuation。如果你需要不同的替换,只需用另一个替换正则表达式,请参阅http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html