C# 程式可統計給定字串中的單詞數
假設我們要統計以下字串中的單詞數 -
str1 = "Hello World!";
現在您需要迴圈,直到字串長度並且在找到 “ “ 時增加變數計數,
, \t 如下所示 -
if(str1[a]==' ' || str1[a]=='
' || str1[a]=='\t') { count++; }
您可以嘗試執行以下程式碼,用 C# 統計給定字串中的單詞數。
示例
using System;
public class Demo {
public static void Main() {
string str1;
int a, count;
str1 = "Hello World!";
a = 0;
count = 1;
while (a <= str1.Length - 1) {
if(str1[a]==' ' || str1[a]=='
' || str1[a]=='\t') {
count++;
}
a++;
}
Console.Write("Total words= {0}
", count);
}
}輸出
Total words= 2
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP