ããã£ã¡ããã«4ãã¤ãæåã®ð©¹ï¼ã¨ã³ããï¼ãéãä»ãã¦ãããã£ã¡ãããä½ã£ã¦ãTwitterã¯ã©ã¤ã¢ã³ãã®æååå¦çãã°ãããã¦éãã§ããããð©¹ï¼ã¨ã³ããï¼åé¡ã¨ããååãã¤ãã¾ããã
StringInfoã¯ã©ã¹ä½¿ãã°ä¾¿å©ã¡ã½ããããããç°¡åãããï¼ã¨æã£ãã
SubstringByTextElementsã¨ãããä»åã®ããã£ã¡ããã®ä¸ã§éè¦ãªã¡ã½ããããªããªã£ã¦ãã¿ããã§ããèªåå®è£ ããã¦ãã³ã¼ããè¦ã¦èªåã ã£ããâ¦ã¨ããã®ãæ¸ãã¦ã¿ã¾ããã
public static class StringExtensions { /// <summary> /// æåæ°ãè¿ã /// </summary> /// <param name="self">対象ã®æåå</param> /// <returns>æåæ°</returns> public static int LengthInTextElements(this string self) { return new StringInfo(self).LengthInTextElements; } /// <summary> /// 1æåãã¤è¿ãæãã®IEãä½ã /// </summary> /// <param name="self">対象ã®æåå</param> /// <param name="index">éå§ä½ç½®</param> /// <returns>IE</returns> public static IEnumerable<string> GetTextElementEnumerable(this string self, int index = 0) { var e = StringInfo.GetTextElementEnumerator(self, index); while (e.MoveNext()) { yield return (string)e.Current; } } /// <summary> /// æå®ããç¯å²ã®æååãåãåºã /// </summary> /// <param name="self">対象ã®æåå</param> /// <param name="startIndex">éå§ä½ç½®</param> /// <param name="length">é·ã</param> /// <returns></returns> public static string SubstringByTextElements(this string self, int startIndex, int length) { var sub = self.GetTextElementEnumerable(startIndex).Take(length).ToArray(); if (sub.Length != length) { throw new ArgumentOutOfRangeException(); } return string.Concat(sub); } }
ã¨ããããGetTextElementEnumeratorã¨ããã¡ã½ãããããã®ã§ãããã使ã£ã¦IE
[TestClass] public class UnitTest1 { [TestMethod] public void LengthInTextElements() { var target = "俺ãð©¹ã ï¼"; Assert.AreEqual(5, target.LengthInTextElements()); } [TestMethod] public void GetTextElementEnumerable() { var target = "俺ãð©¹ã ï¼"; var result = target.GetTextElementEnumerable().ToArray(); Assert.AreEqual("俺", result[0]); Assert.AreEqual("ã", result[1]); Assert.AreEqual("ð©¹", result[2]); Assert.AreEqual("ã ", result[3]); Assert.AreEqual("ï¼", result[4]); } [TestMethod] public void SubString() { var target = "俺ãð©¹ã ï¼"; var result = target.SubstringByTextElements(2, 1); Assert.AreEqual("ð©¹", result); } [TestMethod] public void SubString_ç¯å²å¤() { try { var target = "俺ãð©¹ã ï¼"; var result = target.SubstringByTextElements(2, 1000); Assert.Fail(); } catch (Exception ex) { // Lengthãã¯ã¿åºã¦ãã¨ä¾å¤ãåºã Assert.IsInstanceOfType(ex, typeof(ArgumentOutOfRangeException)); } } }