我需要我的Java程序采用如下字符串:
"This is a sample sentence."
并将其转换为字符串数组,如:
{"this","is","a","sample","sentence"}
没有句号或标点符号(最好)。顺便说一句,字符串输入总是一个句子。
有没有一种简单的方法可以做到这一点,我没有看到?或者我们是否真的必须经常搜索空间并从空格之间的区域(这些是单词)创建新的字符串?
String.split()将完成您想要的大部分工作。然后,您可能需要遍历单词以删除任何标点符号。
例如:
String s = "This is a sample sentence.";
String[] words = s.split("\\s+");
for (int i = 0; i < words.length; i++) {
// You may want to check for a non-word character before blindly
// performing a replacement
// It may also be necessary to adjust the character class
words[i] = words[i].replaceAll("[^\\w]", "");
}
以下是一个代码片段,它将一个句子分成单词并给出其计数。
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class StringToword {
public static void main(String[] args) {
String s="a a a A A";
String[] splitedString=s.split(" ");
Map m=new HashMap();
int count=1;
for(String s1 :splitedString){
count=m.containsKey(s1)?count+1:1;
m.put(s1, count);
}
Iterator<StringToword> itr=m.entrySet().iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
string.replaceAll()无法正确使用与预定义不同的语言环境。至少在jdk7u10。
此示例使用windows cyrillic charset CP1251从textfile创建一个单词字典
public static void main (String[] args) {
String fileName = "Tolstoy_VoinaMir.txt";
try {
List<String> lines = Files.readAllLines(Paths.get(fileName),
Charset.forName("CP1251"));
Set<String> words = new TreeSet<>();
for (String s: lines ) {
for (String w : s.split("\\s+")) {
w = w.replaceAll("\\p{Punct}","");
words.add(w);
}
}
for (String w: words) {
System.out.println(w);
}
} catch (Exception e) {
e.printStackTrace();
}
我已经在某处发布了这个答案,我会再次在这里做。此版本不使用任何主要的内置方法。你有char数组,将其转换为String。希望能帮助到你!
import java.util.Scanner;
public class SentenceToWord
{
public static int getNumberOfWords(String sentence)
{
int counter=0;
for(int i=0;i<sentence.length();i++)
{
if(sentence.charAt(i)==' ')
counter++;
}
return counter+1;
}
public static char[] getSubString(String sentence,int start,int end) //method to give substring, replacement of String.substring()
{
int counter=0;
char charArrayToReturn[]=new char[end-start];
for(int i=start;i<end;i++)
{
charArrayToReturn[counter++]=sentence.charAt(i);
}
return charArrayToReturn;
}
public static char[][] getWordsFromString(String sentence)
{
int wordsCounter=0;
int spaceIndex=0;
int length=sentence.length();
char wordsArray[][]=new char[getNumberOfWords(sentence)][];
for(int i=0;i<length;i++)
{
if(sentence.charAt(i)==' ' || i+1==length)
{
wordsArray[wordsCounter++]=getSubString(sentence, spaceIndex,i+1); //get each word as substring
spaceIndex=i+1; //increment space index
}
}
return wordsArray; //return the 2 dimensional char array
}
public static void main(String[] args)
{
System.out.println("Please enter the String");
Scanner input=new Scanner(System.in);
String userInput=input.nextLine().trim();
int numOfWords=getNumberOfWords(userInput);
char words[][]=new char[numOfWords+1][];
words=getWordsFromString(userInput);
System.out.println("Total number of words found in the String is "+(numOfWords));
for(int i=0;i<numOfWords;i++)
{
System.out.println(" ");
for(int j=0;j<words[i].length;j++)
{
System.out.print(words[i][j]);//print out each char one by one
}
}
}
}
另一种方法是StringTokenizer。例如: -
public static void main(String[] args) {
String str = "This is a sample string";
StringTokenizer st = new StringTokenizer(str," ");
String starr[]=new String[st.countTokens()];
while (st.hasMoreElements()) {
starr[i++]=st.nextElement();
}
}
您可以使用简单的以下代码
String str= "This is a sample sentence.";
String[] words = str.split("[[ ]*|[//.]]");
for(int i=0;i<words.length;i++)
System.out.print(words[i]+" ");
这里的大多数答案都会根据问题将String转换为String Array。但通常我们使用List,所以更有用的是 -
String dummy = "This is a sample sentence.";
List<String> wordList= Arrays.asList(dummy.split(" "));
现在,这可以通过split
完成,因为它需要正则表达式:
String s = "This is a sample sentence with []s.";
String[] words = s.split("\\W+");
这将给出如下词:{"this","is","a","sample","sentence", "s"}
\\W+
将匹配出现一次或多次的所有非字母字符。所以没有必要更换。您也可以检查其他模式。
您可以使用BreakIterator.getWordInstance
查找字符串中的所有单词。
public static List<String> getWords(String text) {
List<String> words = new ArrayList<String>();
BreakIterator breakIterator = BreakIterator.getWordInstance();
breakIterator.setText(text);
int lastIndex = breakIterator.first();
while (BreakIterator.DONE != lastIndex) {
int firstIndex = lastIndex;
lastIndex = breakIterator.next();
if (lastIndex != BreakIterator.DONE && Character.isLetterOrDigit(text.charAt(firstIndex))) {
words.add(text.substring(firstIndex, lastIndex));
}
}
return words;
}
测试:
public static void main(String[] args) {
System.out.println(getWords("A PT CR M0RT BOUSG SABN NTE TR/GB/(G) = RAND(MIN(XXX, YY + ABC))"));
}
输出:
[A, PT, CR, M0RT, BOUSG, SABN, NTE, TR, GB, G, RAND, MIN, XXX, YY, ABC]
你可以使用这个正则表达式分割你的字符串
String l = "sofia, malgré tout aimait : la laitue et le choux !" <br/>
l.split("[[ ]*|[,]*|[\\.]*|[:]*|[/]*|[!]*|[?]*|[+]*]+");
我能想到的最简单和最好的答案是使用java字符串上定义的以下方法 -
String[] split(String regex)
并且只做“这是一个例句”.split(“”)。因为它需要正则表达式,所以您也可以执行更复杂的拆分,其中包括删除不需要的标点符号和其他此类字符。
尝试使用以下内容:
String str = "This is a simple sentence";
String[] strgs = str.split(" ");
这将使用空格作为分割点在字符串数组的每个索引处创建子字符串。
使用string.replace(".", "").replace(",", "").replace("?", "").replace("!","").split(' ')
将代码拆分为不带句点,逗号,问号或感叹号的数组。您可以根据需要添加/删除任意数量的替换呼叫。
试试这个:
String[] stringArray = Pattern.compile("ian").split(
"This is a sample sentence"
.replaceAll("[^\\p{Alnum}]+", "") //this will remove all non alpha numeric chars
);
for (int j=0; i<stringArray .length; j++) {
System.out.println(i + " \"" + stringArray [j] + "\"");
}