koma blog

Unreal Engine 4やUnity 5についての記事を書きます

【Unity】 半角文字と全角文字を変換する

半角文字と全角文字を変換する

//__/__/__/__/__/__/__/__/__/__/__/__/__/__/__/__/__/__/__/__/__/__/__/__/__/__/
//
// ▼ File		StringWidthConverter.cs
//
// ▼ Brief		半角文字と全角文字を変換するスクリプト
//__/__/__/__/__/__/__/__/__/__/__/__/__/__/__/__/__/__/__/__/__/__/__/__/__/__/
using UnityEngine;
using System.Collections;

public class StringWidthConverter : MonoBehaviour
{
    const int ConvertionConstant = 65248;

    static public string ConvertToFullWidth(string halfWidthStr)
    {
        string fullWidthStr = null;

        for (int i = 0; i < halfWidthStr.Length; i++)
        {
            fullWidthStr += (char)(halfWidthStr[i] + ConvertionConstant);
        }

        return fullWidthStr;
    }

    static public string ConvertToHalfWidth(string fullWidthStr)
    {
        string halfWidthStr = null;

        for (int i = 0; i < fullWidthStr.Length; i++)
        {
            halfWidthStr += (char)(fullWidthStr[i] - ConvertionConstant);
        }

        return halfWidthStr;
    }
}

使用例

// 0123abcd
Debug.Log(StringWidthConverter.ConvertToHalfWidth("0123abcd"));

// 4567EFGH
Debug.Log(StringWidthConverter.ConvertToFullWidth("4567EFGH"));

小文字と大文字を変換する

// abcd
Debug.Log("ABCD".ToLower());

// ABCD
Debug.Log("abcd".ToUpper());