计算字符串 C# 中的单词和空格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17812566/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Count words and spaces in string C#
提问by user2592968
I want to count words and spaces in my string. String looks like this:
我想计算字符串中的单词和空格。字符串看起来像这样:
Command do something ptuf(123) and bo(1).ctq[5] v:0,
I have something like this so far
到目前为止我有这样的事情
int count = 0;
string mystring = "Command do something ptuf(123) and bo(1).ctq[5] v:0,";
foreach(char c in mystring)
{
if(char.IsLetter(c))
{
count++;
}
}
What should I do to count spaces also?
我应该怎么做才能计算空格?
采纳答案by Tim Schmelter
int countSpaces = mystring.Count(Char.IsWhiteSpace); // 6
int countWords = mystring.Split().Length; // 7
Note that both use Char.IsWhiteSpace
which assumes other characters than " "
as white-space(like newline
). Have a look at the remarks section to see which exactly .
请注意,两者都使用Char.IsWhiteSpace
which 假定其他字符而不是" "
空格(如newline
)。看看备注部分,看看到底是哪一个。
回答by asafrob
you can use string.Split with a space http://msdn.microsoft.com/en-us/library/system.string.split.aspx
您可以使用带有空格的 string.Split http://msdn.microsoft.com/en-us/library/system.string.split.aspx
When you get a string array the number of elements is the number of words, and the number of spaces is the number of words -1
当你得到一个字符串数组时,元素的数量是单词的数量,空格的数量是单词的数量 -1
回答by Jonesopolis
if you want to count spaces you can use LINQ :
如果你想计算空格,你可以使用 LINQ :
int count = mystring.Count(s => s == ' ');
回答by Daniel M?ller
I've got some ready code to get a list of words in a string: (extension methods, must be in a static class)
我有一些现成的代码来获取字符串中的单词列表:(扩展方法,必须在静态类中)
/// <summary>
/// Gets a list of words in the text. A word is any string sequence between two separators.
/// No word is added if separators are consecutive (would mean zero length words).
/// </summary>
public static List<string> GetWords(this string Text, char WordSeparator)
{
List<int> SeparatorIndices = Text.IndicesOf(WordSeparator.ToString(), true);
int LastIndexNext = 0;
List<string> Result = new List<string>();
foreach (int index in SeparatorIndices)
{
int WordLen = index - LastIndexNext;
if (WordLen > 0)
{
Result.Add(Text.Substring(LastIndexNext, WordLen));
}
LastIndexNext = index + 1;
}
return Result;
}
/// <summary>
/// returns all indices of the occurrences of a passed string in this string.
/// </summary>
public static List<int> IndicesOf(this string Text, string ToFind, bool IgnoreCase)
{
int Index = -1;
List<int> Result = new List<int>();
string T, F;
if (IgnoreCase)
{
T = Text.ToUpperInvariant();
F = ToFind.ToUpperInvariant();
}
else
{
T = Text;
F = ToFind;
}
do
{
Index = T.IndexOf(F, Index + 1);
Result.Add(Index);
}
while (Index != -1);
Result.RemoveAt(Result.Count - 1);
return Result;
}
/// <summary>
/// Implemented - returns all the strings in uppercase invariant.
/// </summary>
public static string[] ToUpperAll(this string[] Strings)
{
string[] Result = new string[Strings.Length];
Strings.ForEachIndex(i => Result[i] = Strings[i].ToUpperInvariant());
return Result;
}
回答by Brad Christie
In addition to Tim's entry, in case you have padding on either side, or multiple spaces beside each other:
除了 Tim 的条目,如果您在任一侧都有填充,或者彼此旁边有多个空格:
Int32 words = somestring.Split( // your string
new[]{ ' ' }, // break apart by spaces
StringSplitOptions.RemoveEmptyEntries // remove empties (double spaces)
).Length; // number of "words" remaining
回答by Gray
Here's a method using regex. Just something else to consider. It is better if you have long strings with lots of different types of whitespace. Similar to Microsoft Word's WordCount.
这是使用正则表达式的方法。只是其他需要考虑的事情。如果您有包含许多不同类型空格的长字符串,那就更好了。类似于 Microsoft Word 的 WordCount。
var str = "Command do something ptuf(123) and bo(1).ctq[5] v:0,";
int count = Regex.Matches(str, @"[\S]+").Count; // count is 7
For comparison,
为了比较,
var str = "Command do something ptuf(123) and bo(1).ctq[5] v:0,";
str.Count(char.IsWhiteSpace)
is 17, while the regex count is still 7.
str.Count(char.IsWhiteSpace)
是 17,而正则表达式计数仍然是 7。
回答by TTT
This will take into account:
这将考虑:
- Strings starting or ending with a space.
- Double/triple/... spaces.
- 以空格开头或结尾的字符串。
- 双/三/...空格。
Assuming that the only word seperators are spaces and that your string is not null.
假设唯一的单词分隔符是空格并且您的字符串不为空。
private static int CountWords(string S)
{
if (S.Length == 0)
return 0;
S = S.Trim();
while (S.Contains(" "))
S = S.Replace(" "," ");
return S.Split(' ').Length;
}
Note: the while loop can also be done with a regex: How do I replace multiple spaces with a single space in C#?
注意:while 循环也可以使用正则表达式完成:如何在 C# 中用单个空格替换多个空格?
回答by Karthick
using namespace;
namespace Application;
class classname
{
static void Main(string[] args)
{
int count;
string name = "I am the student";
count = name.Split(' ').Length;
Console.WriteLine("The count is " +count);
Console.ReadLine();
}
}
回答by Karthick
if you need whitespace count only try this.
如果您只需要空格计数,请尝试此操作。
string myString="I Love Programming";
var strArray=myString.Split(new char[] { ' ' });
int countSpace=strArray.Length-1;