本文介绍了如何计算C#中没有空格的单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 亲爱的先生, 我想在一个句子中计算没有空格的单词,但是我遇到的问题是,当我运行程序空间时,也会计算单词但是我只想算数字请指导。我的C#程序如下。Dear Sir,I want to count words without space in a Sentence but I face a problem that when I run the program space is also count with words but I want count only words Please guide . My C# program is as under.using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Text.RegularExpressions;using System.IO;namespace Static_Method_Count_Word{ class Program { static void Main(string[] args) { Console.WriteLine("Please Enter Any Paragraph ."); string Paragraph = Console.ReadLine(); Count.Coun(Paragraph); Console.ReadLine(); } } class Count { public static void Coun(string Paragraph ) { int i = 0,b=0; int Count2 = 1; for (i = 0; i < Paragraph.Length; i++) { if (Paragraph[i] == ' ') { for (b = i; b < Paragraph.Length; b++) { if (Paragraph[b] != ' ' && Paragraph[b] != '\t') { Count2++; break; } } } }} }} 推荐答案 char[] takeWhiteSpaceSeparators = null;int wordCount = paragraph.Split( takeWhiteSpaceSeparators , StringSplitOptions.RemoveEmptyEntries ) .Length;干杯 Andi CheersAndi // Method returns an integer and gets a string paragraphint GetWords(string paragraph) {// It returns the total number of wordsreturn ( // Splits the paragraph at every occurance of empty string paragraph.Split(new string[] {" "}, // Spliting options let you omit the empty words, like " " StringSplitOptions.RemoveEmptyEntries).Length );} 这将返回段落中的单词总数或字符串的总数。要测试这个程序逻辑,你可以使用这个小提琴: https://dotnetfiddle.net/E1JIy2 [ ^ ]。有关此Split方法签名和其他详细信息的更多信息,请参阅此MSDN文档 [ ^ ]。This would return the total number of words in the paragraph or what so ever the string is. To test this program logic, you can use this fiddle: https://dotnetfiddle.net/E1JIy2[^]. For more on this Split method signature and other details, see this MSDN document[^]. string [] seperator = { " " };string [] words = Paragraph.Split(seperator, StringSplitOptions.RemoveEmptyEntries);int nrofwords = words.Length; 希望这会有所帮助。hope this helps. 这篇关于如何计算C#中没有空格的单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-10 05:38