Lập trình Java - Đếm số từ của xâu ký tự đó
Nhập một xâu ký tự. Đếm số từ của xâu ký tự đó. Thí dụ " Trường học " có 2 từ.
Mã nguồn chương trình:
import java.util.Scanner;
import java.util.StringTokenizer;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author ADMIN
*/
public class Bai34 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner input= new Scanner(System.in);
System.out.println("Nhap vao 1 xau: ");
String str= input.nextLine();
StringTokenizer strToken= new StringTokenizer(str, " ");
System.out.println("So cac tu trong xau la: "+strToken.countTokens());
}
}
Kết quả chạy chương trình:
Nhap vao 1 xau:
Thich Qua Mon
So cac tu trong xau la: 3