gpt4 book ai didi

c# - 如何检查一个数字在文本文件中的特定行中出现了多少次

转载 作者:太空宇宙 更新时间:2023-11-03 20:47:48 25 4
gpt4 key购买 nike

到目前为止,这是我的代码。我知道这很乱,关于如何让它发挥作用有什么想法吗?

我想输出一个数字在文本文件中出现的次数。我想从代码中以字母 Time 开头的特定行获取数字

计算所有 3 个时段的成员总数

文本文件是这样的:

*****************************
Participant: 1

Location: UK
Name: George
Phone Number: 69347653633
Time Slot: 1
*****************************

*****************************
Participant: 2

Location: FR
Name: Alex
Phone Number: 69635343623
Time Slot: 2
*****************************

*****************************
Participant: 3

Location: gr
Name: Maria
Phone Number: 694785896
Time Slot: 3
*****************************

例如,我想要这样的输出:

Total Member Registered for Slot 1: 5

Total Member Registered for Slot 2: 1

Total Member Registered for Slot 3: 3

数字在1到3之间

到目前为止我得到的输出是:

1 was found 1 times
1 was found 1 times
1 was found 1 times
2 was found 1 times
3 was found 1 times
1 was found 1 times
1 was found 1 times
1 was found 1 times
1 was found 1 times
1 was found 1 times

关于如何改进和修复它的任何想法?

public static void ReadNumbers()
{
// Declare list
string[] lines = File.ReadAllLines("text.TXT");

IEnumerable<string> selectLines = lines.Where(line => line.StartsWith("Time"));

foreach (var item in selectLines)
{
var getNumbers = (from num in item where char.IsNumber(num) select num).ToArray();

//Console.WriteLine(new string(getNumbers));
getNumbers.ToArray();

foreach (var group in getNumbers.GroupBy(n => n))
{
Console.WriteLine("{0} was found {1} times", group.Key, group.Count());
}
}
}

最佳答案

更新的答案

我看到您对原始问题进行了一些编辑,并对另一个答案发表了评论,这使得该答案需要进行一些调整。具体来说,您似乎希望结果按升序显示(从插槽 1 到 3)。你还说:

I want also if a slot has not any appear in the file to display Number 2 appeared 0 times.

所以这是我提出的解决方案:

public static void ReadNumbers()
{
string[] lines = File.ReadAllLines("text.TXT");

var groups = lines
.Where(line => line.StartsWith("Time"))
.Select(line => Int32.Parse(new String(line.Where(Char.IsDigit).ToArray())))
.GroupBy(number => number);

for(int i = 1; i <= 3; i ++)
{
var count = groups.FirstOrDefault(group => group.Key == i)?.Count() ?? 0;
Console.WriteLine($"Total Members Registered for Slot {i}: {count}");
}
}

注意:此代码未经测试但应该有效。

我还想补充一点,在接受答案后更改您的问题通常被认为是不礼貌的,这样的更改需要对所述答案进行更改。在这种情况下,您通常会问一个新问题。

原始答案

这是我的做法:

public static void ReadNumbers()
{
string[] lines = File.ReadAllLines("text.TXT");

var groups = lines
.Where(line => line.StartsWith("Time"))
.Select(line => Int32.Parse(new string(line.Where(Char.IsDigit).ToArray())))
.GroupBy(number => number);

foreach(var group in groups)
Console.WriteLine($"{group.Key} appeared: {group.Count()} times");
}

请注意,此方法假定您的文件遵循您在问题中显示的相同格式。

如果您的文件在同一行中出现任何“时间”而没有包含数字,它也会抛出错误。例如,如果您的文件包含如下行:"Time Slot: ""Time Slot: SomeValueThatIsNotANumber" 那么它将抛出。

关于c# - 如何检查一个数字在文本文件中的特定行中出现了多少次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59070141/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com