2

所以我可以在我的文本文件中搜索一个字符串,但是,我想在这个 ArrayList 中对数据进行排序并实现一个算法。是否可以从文本文件中读取并将文本文件中的值 [Strings] 存储在 String[] 数组中。

也可以分开字符串吗?所以不是我的数组有:

[Alice was beginning to get very tired of sitting by her sister on the, bank, and of having nothing to do:]

是否可以将数组设置为:

["Alice", "was" "beginning" "to" "get"...]

.

    public static void main(String[]args) throws IOException
    {
        Scanner scan = new Scanner(System.in);
        String stringSearch = scan.nextLine();

        BufferedReader reader = new BufferedReader(new FileReader("File1.txt"));
        List<String> words = new ArrayList<String>();

        String line;
        while ((line = reader.readLine()) != null) {                
            words.add(line);
        }

        for(String sLine : words) 
        {
            if (sLine.contains(stringSearch)) 
            {
                int index = words.indexOf(sLine);
                System.out.println("Got a match at line " + index);

            }
         }

        //Collections.sort(words);
        //for (String str: words)
        //      System.out.println(str);

        int size = words.size();
        System.out.println("There are " + size + " Lines of text in this text file.");
        reader.close();

        System.out.println(words);

    }
4

2 回答 2

4

也可以分开字符串吗? 是的,您可以将其用于空格来拆分字符串。

 String[] strSplit;
 String str = "This is test for split";
 strSplit = str.split("[\\s,;!?\"]+");

请参阅字符串 API

此外,您还可以逐字阅读文本文件。

 Scanner scan = null;
 try {
     scan = new Scanner(new BufferedReader(new FileReader("Your File Path")));
 } catch (FileNotFoundException e) {
     e.printStackTrace();
 }

 while(scan.hasNext()){
     System.out.println( scan.next() ); 
 }

请参阅扫描仪 API

于 2013-01-09T00:11:05.117 回答
4

要将一行拆分为一个单词数组,请使用以下命令:

String words = sentence.split("[^\\w']+");

正则表达式的[^\w']意思是“不是单词 char 或撇号”

这将捕获带有嵌入撇号的单词,例如“can't”,并跳过所有标点符号。

编辑:

一条评论提出了解析引用的单词的边缘情况,'this'例如this
这是解决方案 - 您必须首先删除包装引号:

String[] words = input.replaceAll("(^|\\s)'([\\w']+)'(\\s|$)", "$1$2$3").split("[^\\w']+");

这是一些带有边缘和角落案例的测试代码:

public static void main(String[] args) throws Exception {
    String input = "'I', ie \"me\", can't extract 'can't' or 'can't'";
    String[] words = input.replaceAll("(^|[^\\w'])'([\\w']+)'([^\\w']|$)", "$1$2$3").split("[^\\w']+");
    System.out.println(Arrays.toString(words));
}

输出:

[I, ie, me, can't, extract, can't, or, can't]
于 2013-01-09T00:38:48.463 回答