Java 从包含以下内容的字符串中计算字数\n

Java 从包含以下内容的字符串中计算字数\n,java,Java,我在下面提到了字符串 String str = "\nArticle\n\nArticle\nArticle"; 我要总数。我怎么能得到这个? 由于字符串包含\n所以总是给出1而不是3来开始,我将向您展示一个简单的示例: String str = "\nArticle\n\nArticle\nArticle"; // Split the String by \n String[] words = str.split("\n"); // Keep the count of words int

我在下面提到了字符串

String str = "\nArticle\n\nArticle\nArticle";
我要总数。我怎么能得到这个?
由于字符串包含\n所以总是给出1而不是3来开始,我将向您展示一个简单的示例:

String str = "\nArticle\n\nArticle\nArticle";

// Split the String by \n
String[] words = str.split("\n");

// Keep the count of words
int wordCount = 0;

for(String word : words){
   // Only count non-empty Strings
   if(!word.isEmpty()) {
       wordCount++;
   }
}

// Check, answer is 3
System.out.println(wordCount);

你一开始是怎么做的?我们如何在看不到的情况下更正您生成的代码。用\n分隔的字数?可能与[1]:和[2]重复。审阅者:您能稍微扩展一下您的问题吗?如果你把你迄今为止所做的尝试、你所做的研究/谷歌搜索以及你目前的解决方案遇到的错误/问题都包括在内,你会得到更多的积极反馈。