Java程序计算句子中的单词数
时间:2020-02-23 14:35:07 来源:igfitidea点击:
在本教程中,我们将看到一个简单的Java程序来计算句子中的单词数。
import java.util.Scanner; public class StringOperator { public static int countWordsinStr(String str){ int count = 1; for(int i=0; i<=str.length()-1; i++){ if(str.charAt(i) == ' ' && str.charAt(i+1)!=' '){ count++; } } return count; } public static void main(String args[]){ String str; Scanner scan = new Scanner(System.in); System.out.print("Enter a Sentence : "); str = scan.nextLine(); System.out.print("Total number of words are " + countWordsinStr(str)); } }
输出:
Enter a Sentence : theitroad is a technical blog. Total number of words are 5