string list = "123";
foreach (char item in list)
{
Console.WriteLine(item);
}
你可以这样,这样做可以处理大部分中文,但不能覆盖所有中文,会出bug。
这里可以看出char最大16bit,而部分中文的unicode是超出16bit的。
我封装了一个MyString来处理
MyString list = new MyString("𠀀𠀁𠀂𠀃");
foreach (int item in list)
{
Console.WriteLine(item);
}
public class MyString : IEnumerable
{
string str = "";
public MyString() { }
public MyString(string str0) { str = str0; }
public IEnumerator GetEnumerator()
{
return new MyStringEnum(str);
}
}
class MyStringEnum : IEnumerator
{
private string list;
int position = -1;
public MyStringEnum(string list)
{
this.list = list;
}
public bool MoveNext()
{
if (0 <= position && position < list.Length)
{
int codePoint = Char.ConvertToUtf32(list, position);
if(codePoint > 0xffff)
position += 2;
else
position++;
}
else
{
position++;
}
return (position < list.Length);
}
public void Reset()
{
position = -1;
}
public object Current
{
get
{
return Char.ConvertToUtf32(list, position);
}
}
}