[英]How to count only letters in a string?
在下一个代码中,我将文本拆分为单词,将它们分别插入表格中并计算每个单词中字母的数量。 问题在于计数器还在每行的开头计数空格,并且给我某些单词错误的值。 我怎样才能准确地仅计算每个单词的字母?
var str = reader1.ReadToEnd();
char[] separators = new char[] {' ', ',', '/', '?'}; //Clean punctuation from copying
var words = str.Split(separators, StringSplitOptions.RemoveEmptyEntries).ToArray(); //Insert all the song words into "words" string
string constring1 = "datasource=localhost;port=3306;username=root;password=123";
using (var conDataBase1 = new MySqlConnection(constring1))
{
conDataBase1.Open();
for (int i = 0; i < words.Length; i++)
{
int numberOfLetters = words[i].ToCharArray().Length; //Calculate the numbers of letters in each word
var songtext = "insert into myproject.words (word_text,word_length) values('" + words[i] + "','" + numberOfLetters + "');"; //Insert words list and length into words table
MySqlCommand cmdDataBase1 = new MySqlCommand(songtext, conDataBase1);
try
{
cmdDataBase1.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
int numberOfLetters = words[i].Trim().ToCharArray().Length; //Calculate the numbers of letters in each word
而不是' '
使用'\\s+'
因为它可以一次匹配一个或多个空格,因此可以分割任意数量的空格字符。
Regex.Split(myString, @"\s+");
这将是一种简单而快速的方法:
int numberOfLetters = words[i].Count(word => !Char.IsWhiteSpace(word));
另一个可以为您节省上面和其余答案的简单解决方案是,首先使用Trim()
,然后进行常规计算,这是因为您声明它仅发生在每一行的开头。
var words = str.Trim().Split(separators, StringSplitOptions.RemoveEmptyEntries);
比您需要的更多是:(没有多余的转换)
int numberOfLetters = words[i].Length;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.