如何获得文本中第一个字符的出现并保持原始顺序?

发布于 2024-10-22 06:16:14 字数 527 浏览 3 评论 0原文

我尝试让文本中出现的第一个字符保持其原始顺序。我尝试使用 LINQ,但我对此很陌生,所以出现了问题,结果很糟糕。

例如我写:“语言”,所以结果将是l-0、a-1、n-2、g-3、u-4、e-7、s-8(出现的数字平均索引)。但我的代码给出:l-0、a-1、n-2、g-3、u-4、e-5、s-6

所以索引号无论如何都是0,1,2,3,4,5。这是我的代码:

char[] result = text.ToLower()
    .Where(char.IsLetter)
    .GroupBy(x => x)
    .Select(g => g.Key).ToArray();

for (int i = 0; i < result.Length; i++)
{
    listView1.Items.Add(result[i].ToString());
    listView1.Items[i].SubItems.Add(i.ToString());
}

I try to get first character occurrence in text keeping their original order. I try to use LINQ but I'm very new in this, so something is wrong, and I have bad result.

For example I write: "languages", so the result would l-0, a-1, n-2, g-3, u-4, e-7, s-8 (digit mean index of occurrence). But my code gives: l-0, a-1, n-2, g-3, u-4, e-5, s-6.

So index number is 0,1,2,3,4,5 no matter what. That's my code:

char[] result = text.ToLower()
    .Where(char.IsLetter)
    .GroupBy(x => x)
    .Select(g => g.Key).ToArray();

for (int i = 0; i < result.Length; i++)
{
    listView1.Items.Add(result[i].ToString());
    listView1.Items[i].SubItems.Add(i.ToString());
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

小红帽 2024-10-29 06:16:14

使用 LINQ 我相信您正在尝试完成以下任务:

string input = "languages";
var query = input.Select((c, i) => new { Char = c, Index = i })
                 .Where(o => Char.IsLetter(o.Char))
                 .GroupBy(o => o.Char)
                 .Select(g => g.First());

foreach (var item in query)
{
    Console.WriteLine("{0}: {1}", item.Char, item.Index);
}

您可以使用重载的 Select 方法来获取每个字符的索引。捕获原始索引后,您可以自由地进一步操作结果。现在,您可以仅过滤字符,按字符对它们进行分组,最后从每个组中获取 First() 项。

Using LINQ I believe you're trying to accomplish the following:

string input = "languages";
var query = input.Select((c, i) => new { Char = c, Index = i })
                 .Where(o => Char.IsLetter(o.Char))
                 .GroupBy(o => o.Char)
                 .Select(g => g.First());

foreach (var item in query)
{
    Console.WriteLine("{0}: {1}", item.Char, item.Index);
}

You can use the overloaded Select method to grab the index of each character. With the original indices captured, you're free to further manipulate the results. Now you can filter for characters only, group them by character and, finally, take the First() item from each group.

寻梦旅人 2024-10-29 06:16:14

我会使用正则表达式:

using System.Text.RegularExpressions;

var q = from ch in text.Distinct()
        select Regex.Match(text, ch.ToString());
foreach (var item in q)
{
    Console.WriteLine("{0}-{1}", item.Value, item.Index);
}

以及非正则表达式替代方案:

var q = from ch in text.Distinct()
        select new { Value = ch, Index = text.IndexOf(ch) };

I would use Regex:

using System.Text.RegularExpressions;

var q = from ch in text.Distinct()
        select Regex.Match(text, ch.ToString());
foreach (var item in q)
{
    Console.WriteLine("{0}-{1}", item.Value, item.Index);
}

And a non-regex alternative:

var q = from ch in text.Distinct()
        select new { Value = ch, Index = text.IndexOf(ch) };
望笑 2024-10-29 06:16:14

你可以试试这个:

string text="languages";
var ints = Enumerable.Range(0,text.Length); 

var firstOccurrences = 
   from couple in text.Zip(ints, (a,b) => new{character=a, index=b})
   where char.IsLetter(couple.character)
   group couple by couple.character into cn
   select new {ch=cn.Key, minindex=cn.Min(c => c.index)};

   foreach(var f in firstOccurrences)
    {
        Console.WriteLine("char:{0} - first occurs: {1}",f.ch,f.minindex);
    }

you can try this:

string text="languages";
var ints = Enumerable.Range(0,text.Length); 

var firstOccurrences = 
   from couple in text.Zip(ints, (a,b) => new{character=a, index=b})
   where char.IsLetter(couple.character)
   group couple by couple.character into cn
   select new {ch=cn.Key, minindex=cn.Min(c => c.index)};

   foreach(var f in firstOccurrences)
    {
        Console.WriteLine("char:{0} - first occurs: {1}",f.ch,f.minindex);
    }
假扮的天使 2024-10-29 06:16:14

您想在这里使用 LINQ 有什么具体原因吗?

您没有保留 LINQ 查询中第一次出现的位置。您得到的只是所有字符的列表。

循环遍历字符串中的字符并使用 Dictionary 存储第一次出现的位置即可完成您的任务。

 public static Dictionary<char, int> FirstOccurence(string str)
    {
        char[] strArr = str.ToCharArray();
        Dictionary<char, int> firstOccur = new Dictionary<char, int>();
        for (int i = 0; i < strArr.Length; i++)
        {
            if (!firstOccur.ContainsKey(strArr[i]))
            {
                firstOccur[strArr[i]] = i;
            }
        }
        return firstOccur;
    }

Is there any specific reason you wanted to use LINQ here?

You are not preserving the position of the first occurence in the LINQ query. What you get is a simply a list of all characters.

Looping through the characters in a string and using a Dictionary<char,int> to store the position of the first occurrence would get your task done.

 public static Dictionary<char, int> FirstOccurence(string str)
    {
        char[] strArr = str.ToCharArray();
        Dictionary<char, int> firstOccur = new Dictionary<char, int>();
        for (int i = 0; i < strArr.Length; i++)
        {
            if (!firstOccur.ContainsKey(strArr[i]))
            {
                firstOccur[strArr[i]] = i;
            }
        }
        return firstOccur;
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文