简体   繁体   中英

Number of line breaks in String

I have a text which is on a website. I am scanning that page and counting the number of several characters, including spaces caused by a line break or "enter press" and "tabs".

I have found an answer for counting the number of lines and such.

How can I do this in java? Counting whitespace is easy, there's a method for it, but not the line breaks or tabs as far as I know.

The website is this http://homepage.lnu.se/staff/jlnmsi/java1/HistoryOfProgramming.txt and I'm counting uppercase and lowercase letters, as well as spaces of any sort.

So far my output is correct for upper and lowercases but not spaces. I'm missing 15, which is exactly the number of line breaks.

public class CountChar 
{
public static void main(String[] args) throws IOException
{
    int upperCase = 0;
    int lowerCase = 0;
    int whitespace = 0;
    int others = 0;

    String url = "http://homepage.lnu.se/staff/jlnmsi/java1/HistoryOfProgramming.txt";
    URL page = new URL(url);
    Scanner in = new Scanner(page.openStream());
    while (in.hasNextLine())
    {
        whitespace++; // THIS IS THE SOLUTION FOR THOSE WHO COME LATER <<<<<
        String line = in.nextLine();
        for (int i = 0; i < line.length(); i++)
        {
            if (Character.isUpperCase(line.charAt(i)))
            {
                upperCase++;
            }
            else if (Character.isLowerCase(line.charAt(i)))
            {
                lowerCase++;
            }
            else if (Character.isWhitespace(line.charAt(i)))
            {
                whitespace++;
            }               
            else
            {
                others++;
            }
        }
    }
    System.out.print(lowerCase + " " + upperCase + " " + whitespace + " " + others);

}
}

If we assume that your data is stored in a String called data :

String[] arrayOfLines= data.split("\r?\t?\n");
int length=arrayOfLines.length-1;

length would give the number of newline characters in data .

您可以使用标准库中的PatternMatcher类来创建一个正则表达式,以搜索要查找的所有字符,并使用find()计算出现的次数,但是不知道这是否比您要复杂的多需要,您可以将字符串拆分为所需的所有必需空白字符...(类似于Krishna Chikkala的答案

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM