C# 如何计算字符串中的字数?
我想数一数字符串中的字数。 如果给定一个字符串:C# 如何计算字符串中的字数?,c#,string,loops,count,word,C#,String,Loops,Count,Word,我想数一数字符串中的字数。 如果给定一个字符串: string str = "Hello! How are you?"; thn输出将为: Number of words in string “Hello! How are you?” is 4. 我使用for循环,这些是我当前的代码 string wordCountStr = ""; int noOfWords = 0; private void btn_Computate4_Click(object sender,
string str = "Hello! How are you?";
thn输出将为:
Number of words in string “Hello! How are you?” is 4.
我使用for循环,这些是我当前的代码
string wordCountStr = "";
int noOfWords = 0;
private void btn_Computate4_Click(object sender, EventArgs e)
{
wordCountStr = tb_Qns4Input.Text.ToString(); //tb_Qns4Input is a textbox.
for (int i = 0; i< wordCountStr.Length; i++)
{
//I don't know how to code here.
}
lbl_ResultQns4.Text = "Number of words in string " + wordCountStr + " is " + noOfWords;
}
假设输入是完美的,您可以简单地在空间上输入,然后得到结果数组的长度
int count = wordCountStr.Split(' ').Length;
str.Split“”。Lengtor str.Countc=>c=''+1,如果您只想计数。我收到此错误。错误1:参数1:无法从“string”转换为“char[]”错误2:与“string.Splitparams char[]”匹配的最佳重载方法具有一些无效属性arguments@TaeyeonUnnie. 哪个错误?@Taeyeounnie。更改为“”我已更新答案好的!最后我用了foreach。将用我的工作答案更新我的问题:D谢谢你的帮助大卫。@Taeyeonnie如果他回答了你的问题,你应该接受他的回答。
int count = wordCountStr.Split(' ').Length;