-2

I am facing a weird file reading a file. The problem is when I read a file, it displays all the data in one line. To heal this, I added line.separators while reading the file. It works fine.see following code

line = br.readLine();
                while (line != null) {
                    String[] parts = line.split(" ");
                    word_count += parts.length;
                    line_count++;
                    fileRead+=line;
                    fileRead+=System.getProperty("line.separator","\n");
                    line = br.readLine();
              } 

Now, the problem comes, when I read the data from fileRead String and count the length of each and every word, then it doesn't give me the correct length/size of some strings like

Let say file contains

Hello, today is Sunday

Thanks

It gives me correct lenth of hello(5) today (5) is(2) Sunday(13). it appends Sunday string like Sunday/n/rThanks. I dont know to get the length of two individuals strings

Code for getting lengths

public void stringLenth(String[] parts) {
        for(int i=0;i<parts.length;i++){
            System.out.println("hello"+parts[i]+"lenth"+parts[i].trim().length());
            parts[i]  = parts[i].replaceAll("\\r|\\n", "");
            if(parts[i].length() < minWordCount  ){
                minWordCount = parts[i].trim().length();
            }
        }
    }

Any idea?

4

1 回答 1

0

使用\\s而不是单个空白字符来拆分您的行。

不要拆分,而是尝试使用带有 a 的正则表达式Matcher并使用\\was 正则表达式来查找所有单词。

于 2013-10-27T16:19:47.440 回答