C# Runes 和 char 数据类型有什么区别?

问题描述 投票:0回答:1

在处理 Unicode 字符时,Runes 和 C# 中的 char 数据类型有什么区别?

使用 Runes 对非 ASCII 字符的处理和操作有何影响?

有人可以提供示例来展示区别并解释使用 Runes 进行 Unicode 字符操作的好处吗?

我尝试利用提供的代码来辨别 Runes 和 char 数据类型在处理 Unicode 字符时的差异。

using System;
using System.Text;

partial class Program
{
    static void Main()
    {
        string input = "Hello 𝓦orld!";

        // Using char data type
        int charCount = input.Length;
        Console.WriteLine("Using char:");
        Console.WriteLine("Character count: " + charCount);

        // Using Rune data type
        int runeCount = GetRuneCount(input);
        Console.WriteLine("\nUsing Rune:");
        Console.WriteLine("Character count: " + runeCount);
    }

    static int GetRuneCount(string input)
    {
        int count = 0;
        RuneEnumerator enumerator = new RuneEnumerator(Encoding.UTF8.GetBytes(input));

        while (enumerator.MoveNext())
        {
            count++;
        }

        return count;
    }
}


public class RuneEnumerator
{
    private readonly byte[] bytes;
    private int index;

    public RuneEnumerator(byte[] bytes)
    {
        this.bytes = bytes;
        index = 0;
    }

    public bool MoveNext()
    {
        if (index >= bytes.Length)
        {
            return false;
        }

        Rune.DecodeFromUtf8(new ReadOnlySpan<byte>(bytes, index, bytes.Length - index), out _, out int bytesConsumed);
        index += bytesConsumed;
        return true;
    }
}
c# .net char c#-8.0
1个回答
0
投票

Runes 是 32 位,而 Char 是 16 位。 请参阅:https://github.com/dotnet/runtime/issues/23578

© www.soinside.com 2019 - 2024. All rights reserved.