gpt4 book ai didi

c# - 从字符串中获取第一个非重复(不同)字符的逻辑

转载 作者:太空狗 更新时间:2023-10-29 22:02:24 24 4
gpt4 key购买 nike

在 c# 中,我想创建一个逻辑,如果我将一个像 abcabda 这样的字符串传递给一个方法,那么它应该从上面的字符串中返回第一个非重复字符,它应该返回 c。我无法将字符串转换为字符数组,然后如何将每个数组字符与字符串进行比较并返回第一个非重复字符。

我可以做成这样吗?

class A
{
static void main()
{
A a=new A();
char ch=a.m1(abcabd);
}
}

class B
{
char m1(string s)
{
string s1=s;
char[] ch1=new char[s.length];
for(int x=0; x<s.length;x++)
{
ch1[x]=s[x];
}
for(int x=0; x<s.length; x++)
{
for(int y=0; y<s.lenth; y++)
{
if(s[x]=ch1[y])
{
/// here i am confused how to create logic for comparison please let me know
// and how to return the character
}
}
}
}
}

最佳答案

您似乎在寻找字符串中第一个计数等于 1 的字符?

using System.Linq;
string str = "abcabda";
char result = str.FirstOrDefault(ch => str.IndexOf(ch) == str.LastIndexOf(ch));

非 LINQ 版本:

    for (int index = 0; index < str.Length; index++)
{
if (str.LastIndexOf(str[index]) == str.IndexOf(str[index]))
{
result = str[index];
break;
}
}

关于c# - 从字符串中获取第一个非重复(不同)字符的逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3994644/

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