LoginSignup
4
4

More than 5 years have passed since last update.

[C#] サロゲートペアを含む文字列の文字数を取得する

Last updated at Posted at 2017-06-11

サロゲートペアを含む文字列の文字数をカウントしたい

@NetSeed さんにコメントでご指摘いただいた方法のほうが良さそうでしたので修正しました

対応方法

以下を使うと良いようです。

StringInfo.LengthInTextElements プロパティ (System.Globalization)

実装例

実装例
public static int CombiningCharactersLength(this string str)
{
    return (new System.Globalization.StringInfo(str)).LengthInTextElements;
}
テスト
[TestMethod]
public void Test_CombiningCharactersLength()
{
    var str = "𩸽";
    Assert.AreEqual(str.CombiningCharactersLength(), 1);
}

参考

文字数を正確にカウントするには?(サロゲート文字対応)[C#、VB] - @IT

以下は古い方法だったようですので参考程度にしてください。


対応方法

System.Globalization.StringInfo.ParseCombiningCharacters(string) を使用する
StringInfo.ParseCombiningCharacters メソッド (String) (System.Globalization)

制御文字のインデックスのリスト(int[]) が返るため、そのLengthを取れば良い

実装例

実装例
public static class StringExtentions
{
    public static int CombiningCharactersLength(this string str)
    {
        return System.Globalization.StringInfo.ParseCombiningCharacters(str).Length;
    }
}
テスト
[TestMethod]
public void Test_CombiningCharactersLength()
{
    var str = "𩸽";
    Assert.AreEqual(str.CombiningCharactersLength(), 1);
}

参考

文字列の長さ(文字数)を取得する: .NET Tips: C#, VB.NET
JavaScriptでのサロゲートペア文字列のメモ - Qiita

4
4
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4