我正在尝试查找数组中重复字符的数量并列出它们。例如,用户输入“这是我的房子”,输出应如下所示:
重复字符数为:3,重复字符为:h i s
我必须使用ToCharArray()
我一直在尝试,但无法正常工作,请您帮忙?
谢谢
这是我的代码:
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
<div id="app">
<div>Empty: {{myString === "" ? 'test' : otherString}}<div>
<div>Non Empty: {{myString !== "" ? 'test' : otherString}}<div>
</div>
答案 0 :(得分:4)
您可以尝试使用linq代替for循环。
GroupBy
进行分组并使用where
得到count
大于1。
var r= str.Replace(" ", "").GroupBy(_ => _).Where(x => x.Count() > 1).Select(x => x.Key);
然后使用string.Join
方法和linq count
而不是循环来获得期望的结果。
Console.Write("type a sentence: ");
String str = Console.ReadLine();
var result = str.Replace(" ", "")
.GroupBy(_ => _)
.Where(x => x.Count() > 1)
.Select(x => x.Key);
Console.WriteLine("number of duplicates: " + result.Count() + "\r" + "duplicates are: " + string.Join(" ",result));
结果
type a sentence: number of duplicates: 3 duplicates are: h i s
答案 1 :(得分:0)
这是没有linq的另一种解决方案:
static void Main(string[] args)
{
string longText = @"your sentence comes here";
foreach (var character in CharacterCount.Count(longText))
{
if(character.Value>1)
Console.WriteLine("{0} - {1}", character.Key, character.Value);
}
}
class CharacterCount
{
public static SortedDictionary<char, ulong> Count(string stringToCount)
{
SortedDictionary<char, ulong> characterCount = new SortedDictionary<char, ulong>();
foreach (var character in stringToCount)
{
if (!characterCount.ContainsKey(character))
characterCount.Add(character, 1);
else
characterCount[character]++;
}
return characterCount;
}
}
答案 2 :(得分:0)
这可能有帮助。
Console.Write("type a sentence: ");
String str = Console.ReadLine();
char[] arr = str.ToCharArray();
int[] count = new int[10000];
for (int j = 0; j < arr.Length; j++)
{
if( arr[j] >= 'a' && arr[j] <= 'z' || arr[j] >= 'A'&& arr[j] <= 'Z' )
{
count[arr[j]]++;
}
}
int ans=0;
for (int j = 0; j < count.Length; j++)
{
if(count[j]>1)
{
ans++;
}
}
Console.Write("Number of duplicates: " + ans +" duplicates are: ");
for (int j = 0; j < count.Length; j++)
{
if(count[j]>1)
{
Console.Write((char)j +" " );
}
}
Console.WriteLine();
}
答案 3 :(得分:0)
This Find to find Duplicates characters And Its Occurrence and I am using Key value pair in C#
/// <summary>
/// Find The Duplicates And Its Occurrence
/// </summary>
/// <param name="inputString"> input String for example
/// "Aassekoopannessyttoodde","Mississippi","raccoonnookkeeper"</param>
private static void FindTheDuplicatesAndItsOccurrence(string inputString)
{
// we used Dictionary to make this collection generic
Dictionary<Char, int> CharCount = new Dictionary<char, int>();
foreach (Char eachLetter in inputString)
{
if (eachLetter != ' ')
{
if (!CharCount.ContainsKey(eachLetter))
{
CharCount.Add(eachLetter, 1);
}
else
{
CharCount[eachLetter]++;
}
}
}
foreach (var item in CharCount)
{
if (item.Value > 1)
{
Console.WriteLine(item.Key + "," + item.Value);
}
}
}