[C#] Unicode 포함 문자열을 변환하는 방법

2014. 5. 21. 17:12Coders

웹 상에서 데이터를 읽을 때 한글 등의 문자열이 유니코드로 넘어올 때가 있습니다. 그럴 때에 이를 콘솔에 뿌릴 경우엔 상관없지만, 이를 데이터화 하여 저장하거나 할 때 한글이나 아무튼 맵핑 되는 문자로 변환해서 넣어줘야 겠죠.


실제 원본 소스는 스택오버플로우(링크)에 있는데요, 여기의 예제는 람다 식을 써서 닷넷 2.0에서는 사용할 수 가 없어 MatchEvaluator 부분만 수정한 겁니다.


.Net 2.0 사용 가능하고, 실제 이 데이터를 콘솔에 찍어 봐야 똑같은 값을 찍습니다.(콘솔이 알아서 변환 해 버림)

실제 데이터 집어 넣을 때 유용합니다.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using System.Text.RegularExpressions;

namespace UnicodeConvert
{
	class Program
	{
		private static Regex DECODING_REGEX =
			new Regex(@"\\u(?<Value>[a-fA-F0-9]{4})",
				RegexOptions.Compiled);
		private const string PLACEHOLDER = @"#!쀍쀍쀍!#";

		static void Main(string[] args)
		{
			string unicodeString =
				"This string contains the unicode character Pi(\u03a0)";
			string decodeString = UnicodeToString(unicodeString);

			Console.WriteLine(unicodeString);
			Console.WriteLine(decodeString);

			Console.ReadLine();
		}

		/// <summary>
		/// Unicode Decoding
		/// </summary>
		/// <param name="str"></param>
		/// <returns></returns>
		public static string UnicodeToString(string str)
		{
			return UnicodeToString(str, 65001);
		}

		/// <summary>
		/// Unicode Decoding
		/// </summary>
		/// <param name="str"></param>
		/// <param name="codePage"></param>
		/// <returns></returns>
		public static string UnicodeToString(string str, int codePage)
		{
			if (string.IsNullOrEmpty(str))
				return str;

			return DECODING_REGEX.Replace(
				str.Replace(@"\\", PLACEHOLDER),
				new MatchEvaluator(CapText)).Replace(PLACEHOLDER, @"\\");
		}

		static string CapText(Match m)
		{
			// Get the matched string.
			return ((char)int.Parse(m.Groups["Value"].Value,
				NumberStyles.HexNumber)).ToString();
		}
	}
}


뭐... 제가 나중에 쉽게 찾아 보려고 메모해 두는 겁니다.