如何使用 C# 在不使用内置函数的情况下返回第一个唯一字符?
创建一个长度为256的空新数组,逐个字符遍历整个字符串并递增新数组中的值。最后遍历整个数组并返回值为1的第一个字符。
示例1
aabccd-→2121→返回计数为1的第一个字符。即b通过与ascii值相减。
示例2
using System;
namespace ConsoleApplication{
public class Arrays{
public char ReturnCharacterOfFirstUniqueCharachter(string s){
int index = -1;
int[] arrayValues = new int[256];
for (int i = 0; i < s.Length; i++){
int value = s[i] - 'a';
arrayValues[value] += 1;
}
for (int i = 0; i < s.Length; i++){
int value = s[i] - 'a';
if (arrayValues[value] == 1){
index = i;
break;
}
}
return s[index];
}
}
class Program{
static void Main(string[] args){
Arrays a = new Arrays();
Console.WriteLine(a.ReturnCharacterOfFirstUniqueCharachter("bbookisgreat"));
Console.ReadLine();
}
}
}输出结果k
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短