gpt4 book ai didi

c# - 计算文本中的字符和单词,是否可以对其进行优化?

转载 作者:太空宇宙 更新时间:2023-11-03 18:04:56 24 4
gpt4 key购买 nike

我想用大文本计算字符数,我用以下代码完成:

string s = textBox.Text;
int chars = 0;
int words = 0;

foreach(var v in s.ToCharArray())
chars++;

foreach(var v in s.Split(' '))
words++;


此代码有效,但使用大文本时似乎很慢,所以我该如何改善呢?

最佳答案

您不需要其他字符数组,可以直接使用String.Length

int chars = s.Length;
int words = s.Split().Length;


旁注:如果不带参数调用 String.Split,则所有 white-space characters都用作分隔符。其中包括空格,制表符和换行符。这不是可能的单词定界符的完整列表,但比 " "更好。

您还将连续的空格算作不同的“单词”。使用 StringSplitOptions.RemoveEmptyEntries

string[] wordSeparators = { "\r\n", "\n", ",", ".", "!", "?", ";", ":", " ", "-", "/", "\\", "[", "]", "(", ")", "<", ">", "@", "\"", "'" }; // this list is probably too extensive, tim.schmelter@myemail.com would count as 4 words, but it should give you an idea
string[] words = s.Split(wordSeparators, StringSplitOptions.RemoveEmptyEntries);
int wordCount = words.Length;

关于c# - 计算文本中的字符和单词,是否可以对其进行优化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34920763/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com