从数组中提取单词

时间:2014-06-08 14:13:20

标签: java

我有这个字符串:  "一,二,三,四," 我想做的是得到一个","两个","三个"在数组空间中,所以当我打印数组时,我得到了一个"一个" " 2" "三&#34 ;.我有这个代码,但我得到的只是" eeeeeeeeeeeeeeeeeee"

 for(int j=0;j<s.length();j++){
    for(int i=0;i<s.length();i++)
        if(Character.isLetter(s.charAt(i))&&s.charAt(i)!=',')
        words[j]=""+s.charAt(i);
    }

3 个答案:

答案 0 :(得分:0)

然后试试这个

   String test = " one, ,two three,4,";
    //replace all digit to blank
    test = test.replaceAll("\\d+", "");
    List<String> splittedText = Splitter.on(",").omitEmptyStrings().trimResults().splitToList(test);
    String combineWords = "";
    for (String word : splittedText) {
        combineWords+=word+" ";
    }

    List<String> finalSplittedWord = Splitter.on(" ").omitEmptyStrings().splitToList(combineWords);
    for (String word : finalSplittedWord) {
        System.out.println(word);
    }


输出
  one
  two
  three

Splitter.on来自Google Guava图书馆。下载jar&amp;在项目中使用它

答案 1 :(得分:0)

这是我的尝试。此方法适用于每种语言和每个空格字符:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Split {

    public static void main(String[] args) {
        String str = " one, two, three, 4,";
        System.out.println(getWords(str));
    }

    public static List<String> getWords(String str) {
        List<String> list = new ArrayList<String>(Arrays.asList(str
            .split("[,\\s+]")));
        list.removeIf(s -> s.isEmpty()
            || !s.chars().allMatch(c -> Character.isAlphabetic(c)));
        return list;
    }
}

输出:

[one, two, three]

但它只能在Java 8中运行。如果你需要它在Java 7中工作,它会更长一点:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class Split {
    public static void main(String[] args) {
        String str = " one, two, three, 4,";
        System.out.println(getWords(str));
    }

    public static List<String> getWords(String str) {
        List<String> list = new ArrayList<String>(Arrays.asList(str.split("[,\\s+]")));

        Iterator<String> it = list.iterator();

        while (it.hasNext()) {
            String part = it.next();
            if (part.isEmpty()) {
                it.remove();
                continue;
            }

            for (int i = 0; i < part.length(); i++) {
                if (!Character.isAlphabetic(part.charAt(i))) {
                    it.remove();
                    continue;
                }
            }
        }

        return list;
    }
}

输出:

[one, two, three]

答案 2 :(得分:-1)

使用String.split()方法:

String[] words = s.split(",");

编辑: 如果你的字符串完全像&#34;一,二,三,四,&#34;,看起来你正在寻找整个单词。这应该有所帮助:

String s = " one, ,two three,4,";
Pattern p = Pattern.compile("([a-zA-Z]+)");
Matcher m = p.matcher(s);
List<String> stringList = new ArrayList<String>();
while (m.find()) {
    stringList.add(m.group(1));
}
String[] words = stringList.toArray(new String[stringList.size()]);