我有一个string[]
,值类似
string[] s = { "saravanan", "Karthick", "Jackson", "saravanan" };
我想看下面的输出
saravanan发生2次
卡尔提克出现过1次
杰克逊发生过1次
如何不使用 List
或Dictionary
这是我到目前为止尝试过的:
int i, j;
String[] s = {"saravanan", "Karthick", "Jackson", "saravanan"}
Console.WriteLine("Number of Times occured Each Values");
for (i = 0; i < s.Length; i++)
{
int count = 0;
for (j = 0; j < s.Length; j++)
{
if (s[i] == (s[j]))
{
count++;
}
}
Console.WriteLine(s[i]+"is count="+count);
}
该代码产生以下输出:
每个值出现的次数
saravananis count = 2
Karthickis count = 1
杰克逊(Jacksonis)count = 1
saravananis count = 2
答案 0 :(得分:5)
通常,我们通过 Linq
解决此类问题(查询) string[] s = new[] {
"saravanan", "Karthick", "Jackson", "saravanan" };
var result = string.Join(Environment.NewLine, s
.GroupBy(item => item)
.Select(chunk => $"{chunk.Key} occures {chunk.Count()} times"));
Console.Write(result);
在嵌套循环(您当前的代码)的情况下,不要打印几次相同的名称。让我们介绍一下bool appeared
,如果名字之前出现过
string[] s = new[] {
"saravanan", "Karthick", "Jackson", "saravanan" };
for (i = 0; i < s.Length; i++) {
int count = 0;
bool appeared = false;
for (j = 0; j < s.Length; j++) {
if (s[i] == (s[j])) {
// Names are same. Do we have the name before?
if (j < i) {
// If yes we have no need to loop any more
appeared = true;
break;
}
count++;
}
}
// if name has been appeared already we shouldn't print it out
if (!appeared)
Console.WriteLine(s[i] + "is count=" + count);
}
答案 1 :(得分:2)
由于您不希望"saravanan"
在输出中出现两次。然后,您可以使用一个空字符串作为前哨值。当您发现增加计数的匹配项时,请将该元素清空,并进行检查以在以后运行时跳过该元素。
using System;
public class Program
{
public static void Main()
{
string[] s = { "saravanan","KArthick","Jackson","saravanan" };
for (int i = 0; i < s.Length; i++)
{
// Skip empty element
if (string.IsNullOrEmpty(s[i]))
{
continue;
}
int count = 1;
for (int j = i + 1; j < s.Length; j++)
{
// Skip empty element
if (string.IsNullOrEmpty(s[i]))
{
continue;
}
if (s[i] == s[j])
{
count++;
// Clear the element to indicate the element as already been counted
s[j] = string.Empty;
}
}
Console.WriteLine("{0} occurs {1} times", s[i], count);
}
}
}
结果
saravanan occurs 2 times
KArthick occurs 1 times
Jackson occurs 1 times
答案 2 :(得分:2)
您可以使用linq组选项,如下所示:
String[] s = {"saravanan", "Karthick", "Jackson", "saravanan"};
Console.WriteLine("Number of Times occured Each Values");
var groupArray = s.GroupBy(x => x);
foreach (var group in groupArray)
{
Console.WriteLine(group.Key + "is count=" + group.Count());
}