我需要找到至少包含一个字母的单词数 "A" .帮助我优化 C# 中的代码

  • 本文关键字:单词数 优化 代码 帮助 包含一 c#
  • 更新时间 :
  • 英文 :


`

namespace Program
{
class Program
{
static void Main(string[] args)
{
Console.Write("s: ");
string s = Console.ReadLine();
int count = 0; 
string[] sp = s.Split(new Char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
foreach (string s1 in sp)
{  
if (s[s.Length-1] == 'А')
count++;
}
Console.WriteLine(count);            
}
}
}

`

我的代码有效,但前提是第一个字符是";A";我需要它工作,即使第一个字符不是A.帮助

您可以使用LINQ

string s = Console.ReadLine();
var count = s.Split(' ').Count(c=>c.Contains('A'));
Console.WriteLine(count);  

你不断地比较同一件事。您需要检查您迭代的每个字符串中的字符。使用ToUpper()意味着输入中大小写"a"和小写"a"的计数都将增加。

解决方案:

public static void Main()
{
Console.Write("s: ");
string s = Console.ReadLine();
int count = 0;
string[] sp = s.Split(new Char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string s1 in sp)
{
if (s1.ToUpper().Contains('A'))
count++;
}
Console.WriteLine(count);
}

你必须这样做。

string[] arr = new string[] { "Abc", "axy", "Abd"};
int count = 0;
foreach (string s1 in arr)
{
if (s1.Contains('A'))
count++;
}

如果您想运行for循环而不是foreach,请这样做。

for (int i = 0; i <arr.Length; i++)
{
if (arr[i].Contains('A'))
count++;
}

如果您正在查找不区分大小写的Contains,请遵循此答案。

让我们查询文本:首先,让匹配单词;让单词成为

的非空字母序列

然后我们可以Count(在Linq的帮助下)单词Contains字符'A':

using System.Linq;
using System.Text.RegularExpressions;
...
Console.Write("s: ");
int count = Regex
.Matches(Console.ReadLine(), @"p{L}+")
.Cast<Match>()
.Count(match => match.Value.Contains('A'));
Console.WriteLine(count);          

如果您想要不区分大小写的条件(即计数包含'a''A'的单词),您可以将最后一个.Count作为

.Count(match => match.Value.Contains('A') || match.Value.Contains('a'));

我认为这听起来是正则表达式的一个很好的用例。

下面的代码将用数字3填充numberOfMatches,这正是我所期望的。

var text = "This is a text which contains words with the letter A";
var matches = Regex.Matches(text, "\w*a+\w*", RegexOptions.IgnoreCase);
var numberOfMatches = matches.Count();

不使用Linq、Split、Contains、IndexOf、新的tmp数组或任何内置的helper,这几行也会得到包含任何字符的字数。。。。

//           1   2        3        4           5      6         7
var str = "That fat fox started to accumulate marias fancy cheddar";
char f = 'A';
var cnt = 0;
var srch = f;
foreach (var c in str) {
if (char.ToUpperInvariant(c) == char.ToUpperInvariant(srch)) {
if (srch == f) {
cnt++;
srch = ' ';
}
else {
srch = f;
}
}
}
Console.WriteLine("{0} words containing '{1}' in '{2}' (ignoring casing)", cnt, f, str);

最新更新