#include <stdio.h>//c語言
#include <iostream>//c++
int main(){
char[] str = "hello everyone nihao!";
int count = 0;//用於統計空格個數以此來計算單詞數量
if(str[0] == 0){//如果字符串為空
fprintf("單詞個數為%d",count);//c語言
std::cout<<"單詞個數為"<<count<<endl;//c++
return 0;
}
count++;//若字符串不為空則默認至少有壹個單詞
for(int i=0;;i++){
if(str[i] == 0)//字符串結束標誌的ASCII碼的值為0
break;
if(str[i] == ' ')//若遇到空格字符
count++;
}
fprintf("單詞個數為%d",count);//c語言
std::cout<<"單詞個數為"<<count<<endl;//c++
return 0;
}
如果是java的話
class Solution {
public static void main() {
String str = "hello everyone nihao!";
if (str.isEmpty()) {// 若字符串為空
System.out.println("單詞個數為0");
return;
}
System.out.println("單詞個數是:" + str.split(" ").length);
}
}
如果是C#的話跟java差不多
using System;
class Solution {
public static void main(string[] args) {
string str = "hello everyone nihao!";
if (str.length()==0) {// 若字符串為空
Console.WriteLine("單詞個數為0");
return;
}
Console.WriteLine("單詞個數是:" + str.split(' ').length);
}
}
Python
if __name__ == "__main__":
str = "hello everyone nihao!"
if str=="":
print("單詞個數為0")
print(len(str.split(' ')))