算上句子的话?

时间:2017-08-13 21:35:22

标签: java arrays java-6

我想计算每个句子的单词数我写代码但计算句子中每个单词的字符这个我的代码

let client = TCPClient(address: "192.168.0.50", port: 8080)
switch client.connect(timeout: 1) {
  case .success:
    switch client.send(string: "GET / HTTP/1.0\n\n" ) {
      case .success:
        guard let data = client.read(1024*10) else { return }

        if let response = String(bytes: data, encoding: .utf8) {
          print(response)
        }
      case .failure(let error):
        print(error)
    }
  case .failure(let error):
    print(error)
}

2 个答案:

答案 0 :(得分:1)

String[] count_words= sentences.split(" ");将输入参数拆分为" ",这意味着此数组的长度是单词的数量。只需打印出长度。

public static void main(String[] args) {
    Scanner sca = new Scanner(System.in);
    System.out.println("Please type some words, then press enter: ");
    String sentences= sca.nextLine();
    String[] count_words= sentences.split(" ");
    System.out.println("number of word is "+ count_words.length);
}

示例:

oliverkoo@olivers-MacBook-Pro ~/Desktop/untitled folder $ java Main
Please type some words, then press enter: 
my name is oliver
number of word is 4

答案 1 :(得分:0)

方法调用count.length()返回每个单词的长度,因为循环将每个单词分配给变量count。 (这个变量名称非常令人困惑。)

如果您想要句子中的单词数,则需要count_words数组的大小,即count_words.length