【发布时间】:2021-06-23 16:33:22
【问题描述】:
我正在尝试获取单词的第一个字母和最后一个字母之间的唯一字符数。例如:如果我输入 Yellow 预期的输出是 Y3w,如果我输入 People,输出应该是 P4e,如果我输入 Money,输出应该是 M3y。这是我尝试过的:
//var strArr = wordToConvert.Split(' ');
string[] strArr = new[] { "Money","Yellow", "People" };
List<string> newsentence = new List<string>();
foreach (string word in strArr)
{
if (word.Length > 2)
{
//ignore 2-letter words
string newword = null;
int distinctCount = 0;
int k = word.Length;
int samecharcount = 0;
int count = 0;
for (int i = 1; i < k - 2; i++)
{
if (word.ElementAt(i) != word.ElementAt(i + 1))
{
count++;
}
else
{
samecharcount++;
}
}
distinctCount = count + samecharcount;
char frst = word[0];
char last = word[word.Length - 1];
newword = String.Concat(frst, distinctCount.ToString(), last);
newsentence.Add(newword);
}
else
{
newsentence.Add(word);
}
}
var result = String.Join(" ", newsentence.ToArray());
Console.WriteLine("Output: " + result);
Console.WriteLine("----------------------------------------------------");
使用此代码,我得到了 Yellow 的预期输出,但似乎不适用于 People 和 Money。我可以做些什么来解决这个问题,或者我想知道是否有更好的方法来做到这一点,例如使用 LINQ/Regex。
【问题讨论】:
-
为什么 Yellow 不会产生 Y4w?
-
@Maxqueue 因为程序应该只计算第一个和最后一个字符之间的唯一字符,在这种情况下 *ello 包含双 L,所以它只计算一次。
-
Linq 你可以简单地做一个像
var result = word.First().ToString() + word.Substring(1, word.Length - 2).ToLower().Distinct().Count().ToString() + word.Last().ToString();这样的1 liner -
您要么增加计数,要么增加相同的字符计数,最终将其汇总为不同的计数。然而,通过你实现它的方式,你总是会得到 distinctCount 等于 k-2。您可能只想总结我假设的其中一个
标签: c# .net linq console-application