public bool PosTest3()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest3: The string has a combining character");

        try
        {
            string str = "a\u20D1";
            TextElementEnumerator TextElementEnumerator = StringInfo.GetTextElementEnumerator("13229^a\u20D1a");
            for (int i = 0; i < 7; i++)
            {
                TextElementEnumerator.MoveNext();
            }
            if (TextElementEnumerator.Current.ToString() != str)
            {
                TestLibrary.TestFramework.LogError("007", "The result is not the value as expected,the current is: " + TextElementEnumerator.Current.ToString());
                retVal = false;
            }
            TextElementEnumerator.MoveNext();
            if (TextElementEnumerator.MoveNext())
            {
                TestLibrary.TestFramework.LogError("008", "The result is not the value as expected,the current is: " + TextElementEnumerator.Current.ToString());
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("009", "Unexpected exception: " + e);
            retVal = false;
        }

        return(retVal);
    }
    public bool PosTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest1: The argument is a random string,and start at a random index");

        try
        {
            string str   = TestLibrary.Generator.GetString(-55, true, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH);
            int    len   = str.Length;
            int    index = this.GetInt32(8, len);
            TextElementEnumerator TextElementEnumerator = StringInfo.GetTextElementEnumerator(str, index);
            TextElementEnumerator.MoveNext();
            for (int i = 0; i < len - index; i++)
            {
                if (TextElementEnumerator.Current.ToString() != str[i + index].ToString())
                {
                    TestLibrary.TestFramework.LogError("001", "The result is not the value as expected,the str is: " + str[i + index]);
                    retVal = false;
                }
                TextElementEnumerator.MoveNext();
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
            retVal = false;
        }

        return(retVal);
    }
    public bool PosTest2()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest2: The string has a surrogate pair");

        try
        {
            string str = "\uDBFF\uDFFF";
            TextElementEnumerator TextElementEnumerator = StringInfo.GetTextElementEnumerator("s\uDBFF\uDFFF$", 1);
            TextElementEnumerator.MoveNext();
            if (TextElementEnumerator.Current.ToString() != str)
            {
                TestLibrary.TestFramework.LogError("003", "The result is not the value as expected,the current is: " + TextElementEnumerator.Current.ToString());
                retVal = false;
            }
            TextElementEnumerator.MoveNext();
            if (TextElementEnumerator.Current.ToString() != "$")
            {
                TestLibrary.TestFramework.LogError("004", "The result is not the value as expected");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("005", "Unexpected exception: " + e);
            retVal = false;
        }

        return(retVal);
    }
Esempio n. 4
0
        /// <summary>
        /// Reads a text-element from the input and moves forward. This also
        /// converts '\r\n' to '\n' and changes the Position and Line.
        /// </summary>
        /// <returns>The text-element that was read or null if at the end.</returns>
        protected virtual string ReadElement()
        {
            string ret = null;

            try
            {
                ret = input.GetTextElement();
                input.MoveNext();
            }
            catch (Exception) { }

            if (ret == null)
            {
                return(null);
            }

            Position += ret.Length;
            if (ret == "\r" || ret == "\n")
            {
                if (ret == "\r")
                {
                    string temp = PeekElement();
                    if (temp == "\n")
                    {
                        input.MoveNext();
                    }
                    ret = "\n";
                }
                Line++;
                Position = 1;
            }
            return(ret);
        }
        public void TestSurrogatePair()
        {
            string str = "\uDBFF\uDFFF";
            TextElementEnumerator TextElementEnumerator = StringInfo.GetTextElementEnumerator("s\uDBFF\uDFFF$", 1);

            TextElementEnumerator.MoveNext();
            Assert.Equal(str, TextElementEnumerator.Current.ToString());
            TextElementEnumerator.MoveNext();
            Assert.Equal("$", TextElementEnumerator.Current.ToString());
        }
        public void TestCombiningCharacter()
        {
            string str = "a\u20D1";
            TextElementEnumerator TextElementEnumerator = StringInfo.GetTextElementEnumerator("13229^a\u20D1a", 6);

            TextElementEnumerator.MoveNext();
            Assert.Equal(str, TextElementEnumerator.Current.ToString());
            TextElementEnumerator.MoveNext();
            Assert.Equal("a", TextElementEnumerator.Current.ToString());
            Assert.False(TextElementEnumerator.MoveNext());
        }
Esempio n. 7
0
        /// <summary>
        /// 返回指定字符串的字符顺序是相反的字符串。
        /// </summary>
        /// <param name="str">字符反转的字符串。</param>
        /// <returns>字符反转后的字符串。</returns>
        /// <remarks>参考了 Microsoft.VisualBasic.Strings.StrReverse 方法的实现。</remarks>
        public static string Reverse(this string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return(string.Empty);
            }
            int len = str.Length;
            int end = len - 1;
            int i   = 0;

            char[] strArr = new char[len];
            while (end >= 0)
            {
                switch (char.GetUnicodeCategory(str[i]))
                {
                case UnicodeCategory.Surrogate:
                case UnicodeCategory.NonSpacingMark:
                case UnicodeCategory.SpacingCombiningMark:
                case UnicodeCategory.EnclosingMark:
                    // 字符串中包含组合字符,翻转时需要保证组合字符的顺序。
                    // 为了能够包含基字符,回退一位。
                    if (i > 0)
                    {
                        i--;
                        end++;
                    }
                    TextElementEnumerator textElementEnumerator = StringInfo.GetTextElementEnumerator(str, i);
                    textElementEnumerator.MoveNext();
                    int idx = textElementEnumerator.ElementIndex;
                    while (end >= 0)
                    {
                        i = idx;
                        if (textElementEnumerator.MoveNext())
                        {
                            idx = textElementEnumerator.ElementIndex;
                        }
                        else
                        {
                            idx = len;
                        }
                        for (int j = idx - 1; j >= i; strArr[end--] = str[j--])
                        {
                            ;
                        }
                    }
                    goto EndReverse;
                }
                // 直接复制。
                strArr[end--] = str[i++];
            }
EndReverse:
            return(new string(strArr));
        }
Esempio n. 8
0
        /// <summary>
        /// Gets the string representation for a particular day in the week.
        /// </summary>
        /// <param name="weekDay">Specifies the day of the week.</param>
        /// <returns>the string representation for the specified day.</returns>
        internal protected virtual string GetDayHeaderString(int weekDay)
        {
            DateTimeFormatInfo dateLocalInfo = this.Calendar.DateTimeFormat;
            DayNameFormat      dayFormat     = this.Calendar.DayNameFormat;
            string             dayString     = String.Empty;

            switch (dayFormat)
            {
            case DayNameFormat.Full:
            {
                dayString = dateLocalInfo.GetDayName((DayOfWeek)weekDay);
                break;
            }

            case DayNameFormat.FirstLetter:
            {
                string str = dateLocalInfo.ShortestDayNames[weekDay];
                TextElementEnumerator iter = StringInfo.GetTextElementEnumerator(str);
                iter.MoveNext();
                dayString = iter.Current.ToString();
                break;
            }

            case DayNameFormat.FirstTwoLetters:
            {
                string str = dateLocalInfo.ShortestDayNames[weekDay];
                TextElementEnumerator iter = StringInfo.GetTextElementEnumerator(str);
                iter.MoveNext();
                StringBuilder ftl = new StringBuilder(iter.Current.ToString());
                if (iter.MoveNext())         //in case of Arabic cultures
                {
                    ftl.Append(iter.Current.ToString());
                }
                dayString = ftl.ToString();
                break;
            }

            case DayNameFormat.Short:
            {
                dayString = dateLocalInfo.GetAbbreviatedDayName((DayOfWeek)weekDay);
                break;
            }

            case DayNameFormat.Shortest:
            default:
            {
                dayString = dateLocalInfo.ShortestDayNames[weekDay];
                break;
            }
            }
            return(dayString);
        }
        public void TestRandomString()
        {
            string str = _generator.GetString(-55, true, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH);
            TextElementEnumerator TextElementEnumerator = StringInfo.GetTextElementEnumerator(str);
            int len = str.Length;

            TextElementEnumerator.MoveNext();
            for (int i = 0; i < len; i++)
            {
                Assert.Equal(str[i].ToString(), TextElementEnumerator.Current.ToString());
                TextElementEnumerator.MoveNext();
            }
        }
        public void TestRandomIndex()
        {
            string str   = _generator.GetString(-55, true, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH);
            int    len   = str.Length;
            int    index = this.GetInt32(8, len);
            TextElementEnumerator TextElementEnumerator = StringInfo.GetTextElementEnumerator(str, index);

            TextElementEnumerator.MoveNext();
            for (int i = 0; i < len - index; i++)
            {
                Assert.Equal(str[i + index].ToString(), TextElementEnumerator.Current.ToString());
                TextElementEnumerator.MoveNext();
            }
        }
Esempio n. 11
0
        public static SortedList <int, byte> ToCharVector(this string word)
        {
            var vec = new SortedList <int, byte>();
            TextElementEnumerator charEnum = StringInfo.GetTextElementEnumerator(word);

            while (charEnum.MoveNext())
            {
                var element   = charEnum.GetTextElement().ToCharArray();
                int codePoint = 0;

                foreach (var c in element)
                {
                    codePoint += c;
                }

                if (vec.ContainsKey(codePoint))
                {
                    vec[codePoint] += 1;
                }
                else
                {
                    vec[codePoint] = 1;
                }
            }
            return(vec);
        }
Esempio n. 12
0
 public static IEnumerable <string> ToEnumerable(this TextElementEnumerator enumerator)
 {
     while (enumerator.MoveNext())
     {
         yield return(enumerator.GetTextElement());
     }
 }
    // Returns true if the expected result is right
    // Returns false if the expected result is wrong

    public bool PosTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest1: Calling Reset method.");
        try
        {
            // Creates and initializes a String containing the following:
            //   - a surrogate pair (high surrogate U+D800 and low surrogate U+DC00)
            //   - a combining character sequence (the Latin small letter "a" followed by the combining grave accent)
            //   - a base character (the ligature "")
            String myString = "\uD800\uDC00\u0061\u0300\u00C6";
            // Creates and initializes a TextElementEnumerator for myString.
            TextElementEnumerator myTEE = StringInfo.GetTextElementEnumerator(myString);
            myTEE.Reset();
            myTEE.MoveNext();
            if (myTEE.ElementIndex != 0)
            {
                TestLibrary.TestFramework.LogError("001.1", " Calling Reset method ,the ElementIndex should return 0.");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e);
            retVal = false;
        }

        return(retVal);
    }
Esempio n. 14
0
    public static string replaceextendedchars(String s, Hashtable asciilookup)
    {
        // This StringBuilder holds the output results.
        StringBuilder sb = new StringBuilder();

        // Use the enumerator returned from GetTextElementEnumerator
        // method to examine each real character.
        TextElementEnumerator charEnum = StringInfo.GetTextElementEnumerator(s);

        while (charEnum.MoveNext())
        {
            //sb.Append(char.ConvertToUtf32(charEnum.GetTextElement(), 0).ToString());
            //sb.Append(", ");
            if (asciilookup.ContainsKey(char.ConvertToUtf32(charEnum.GetTextElement(), 0)))
            {
                sb.Append(asciilookup[char.ConvertToUtf32(charEnum.GetTextElement(), 0)]);
            }
            else
            {
                sb.Append(charEnum.GetTextElement());
            }
        }

        return(sb.ToString());
    }
Esempio n. 15
0
        private static List <string> GenerateIndividualMessages(string content)
        {
            List <string>         allMessages   = new();
            int                   numBytes      = 0;
            StringBuilder         stringBuilder = new();
            StringBuilder         wordBuilder   = new();
            TextElementEnumerator te            = StringInfo.GetTextElementEnumerator(content);

            while (te.MoveNext())
            {
                string teString   = te.GetTextElement();
                int    teNumBytes = teString.EnumerateRunes().Sum(x => x.Utf8SequenceLength);
                numBytes += teNumBytes;
                if (numBytes >= 2000)
                {
                    allMessages.Add(stringBuilder.ToString());
                    stringBuilder.Clear();
                    numBytes = teNumBytes;
                }
                wordBuilder.Append(teString);
                if (string.IsNullOrWhiteSpace(teString))
                {
                    stringBuilder.Append(wordBuilder);
                    wordBuilder.Clear();
                }
            }

            allMessages.Add(stringBuilder.Append(wordBuilder).ToString());
            return(allMessages);
        }
 /// <summary>
 /// Converts a <see cref="TextElementEnumerator"/> to an Enumerable.
 /// </summary>
 /// <typeparam name="T">The expected Enumerable type.</typeparam>
 /// <param name="enumerator">The original Enumerator.</param>
 /// <returns>The enumerable.</returns>
 public static IEnumerable <T> AsEnumerable <T>(this TextElementEnumerator enumerator) where T : class
 {
     while (enumerator.MoveNext())
     {
         yield return(enumerator.Current as T);
     }
 }
Esempio n. 17
0
        //------------------------------------------------------------------------------------------------
        //PassWordのテキストボックスの文字入力制限
        //------------------------------------------------------------------------------------------------
        private void textBox3_PassWord_TextChanged(object sender, EventArgs e)
        {
            string moji = this.textBox3_PassWord.Text;

            //文字の列挙オブジェクト
            TextElementEnumerator charEnum = StringInfo.GetTextElementEnumerator(moji);

            //解析済の文字を入れるオブジェクト
            StringBuilder AnalyzedMoji = new StringBuilder();

            while (true)
            {
                // 取得する文字がない
                if (charEnum.MoveNext() == false)
                {
                    break;
                }

                //一文字ずつ正規表現で処理
                //半角英数字でなければ削除される
                AnalyzedMoji.Append(IsAlphanumeric(Convert.ToString(charEnum.Current)));
            }

            textBox3_PassWord.Text = AnalyzedMoji.ToString();
        }
Esempio n. 18
0
        private void TestMultiReadingWithString()
        {
            // 讀取多音字資料檔.
            string multiReadingChars = File.ReadAllText(lblMultiReadingFileName.Text);

            DateTime startTime         = DateTime.Now;
            int      multiReadingCount = 0;

            using (StreamReader sr = new StreamReader(txtInFileName.Text))
            {
                string line = sr.ReadLine();
                while (line != null)
                {
                    TextElementEnumerator itor = StringInfo.GetTextElementEnumerator(line);
                    while (itor.MoveNext())
                    {
                        string hanChar = itor.GetTextElement();
                        if (multiReadingChars.IndexOf(hanChar) >= 0)
                        {
                            multiReadingCount++;
                        }
                    }
                    line = sr.ReadLine();
                }
            }
            DateTime endTime = DateTime.Now;

            txtMsg.AppendText("\r\n判斷多音字-使用 String 類別:");
            txtMsg.AppendText("\r\n  共發現 " + multiReadingCount + " 個多音字。");
            txtMsg.AppendText("\r\n  時間: " + (endTime - startTime).ToString());
        }
Esempio n. 19
0
        private void TestMultiReadingWithPhoneticData()
        {
            // 讀取注音資料檔.
            ChinesePhoneticData phoneData = new ChinesePhoneticData();

            phoneData.LoadFromFile(lblPhoneFileName.Text);

            DateTime startTime         = DateTime.Now;
            int      multiReadingCount = 0;

            using (StreamReader sr = new StreamReader(txtInFileName.Text))
            {
                string line = sr.ReadLine();
                while (line != null)
                {
                    TextElementEnumerator itor = StringInfo.GetTextElementEnumerator(line);
                    while (itor.MoveNext())
                    {
                        string hanChar = itor.GetTextElement();
                        if (phoneData.IsMultiReading(hanChar))
                        {
                            multiReadingCount++;
                        }
                    }
                    line = sr.ReadLine();
                }
            }
            DateTime endTime = DateTime.Now;

            txtMsg.AppendText("\r\n判斷多音字-使用 Huanlin.TextServices.ChinesePhoneticData 類別:");
            txtMsg.AppendText("\r\n  共發現 " + multiReadingCount + " 個多音字。");
            txtMsg.AppendText("\r\n  時間: " + (endTime - startTime).ToString());
        }
Esempio n. 20
0
    public bool NegTest2()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("NegTest2: The enumerator is positioned  after the last text element.");
        try
        {
            String myString = "\uD800\uDC00\u0061\u0300\u00C6";

            // Creates and initializes a TextElementEnumerator for myString.
            TextElementEnumerator myTEE = StringInfo.GetTextElementEnumerator(myString);
            myTEE.Reset();
            string acutalValue = null;
            while (myTEE.MoveNext())
            {
                acutalValue = myTEE.Current.ToString();
            }
            acutalValue = myTEE.Current.ToString();
            TestLibrary.TestFramework.LogError("102.1", " InvalidOperationException should be caught.");
            retVal = false;
        }
        catch (InvalidOperationException)
        {
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("102.0", "Unexpected exception: " + e);
            retVal = false;
        }

        return(retVal);
    }
Esempio n. 21
0
        private void WrapWord(Graphics g, Font font, float width, int index)
        {
            Word word = FWords[index];
            TextElementEnumerator charEnum = StringInfo.GetTextElementEnumerator(word.Text);
            string text = "";

            while (charEnum.MoveNext())
            {
                string textElement = charEnum.GetTextElement();
                float  textWidth   = g.MeasureString(text + textElement, font).Width;

                if (textWidth > width)
                {
                    if (text == "")
                    {
                        text = textElement;
                    }
                    Word newWord = new Word(word.Text.Substring(text.Length), word.OriginalTextIndex + text.Length);
                    word.Text = text;
                    FWords.Insert(index + 1, newWord);
                    return;
                }
                else
                {
                    text += textElement;
                }
            }
        }
Esempio n. 22
0
        public void PosTest1()
        {
            // Creates and initializes a String containing the following:
            //   - a surrogate pair (high surrogate U+D800 and low surrogate U+DC00)
            //   - a combining character sequence (the Latin small letter "a" followed by the combining grave accent)
            //   - a base character (the ligature "")
            String myString = "\uD800\uDC00\u0061\u0300\u00C6";

            string[] expectValue = new string[5];
            expectValue[0] = "\uD800\uDC00";
            expectValue[1] = "\uD800\uDC00";
            expectValue[2] = "\u0061\u0300";
            expectValue[3] = "\u0061\u0300";
            expectValue[4] = "\u00C6";
            // Creates and initializes a TextElementEnumerator for myString.
            TextElementEnumerator myTEE = StringInfo.GetTextElementEnumerator(myString);

            myTEE.Reset();
            string actualValue = null;

            while (myTEE.MoveNext())
            {
                actualValue = myTEE.GetTextElement();
                Assert.Equal(expectValue[myTEE.ElementIndex], actualValue);
            }
        }
Esempio n. 23
0
        /// <summary>
        /// Reverse a string.
        /// </summary>
        /// <param name="value">The string to reverse.</param>
        /// <param name="unicode">Consider unicode characters when reversing.</param>
        /// <returns>The value of <paramref name="value"/> reversed.</returns>
        public static string Reverse(this string value, bool unicode)
        {
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }

            if (value == string.Empty)
            {
                return(value);
            }

            if (!unicode)
            {
                return(Reverse(value));
            }

            TextElementEnumerator enumerator = StringInfo.GetTextElementEnumerator(value);
            List <string>         elements   = new List <string>();

            while (enumerator.MoveNext())
            {
                elements.Add(enumerator.GetTextElement());
            }

            elements.Reverse();

            return(string.Concat(elements));
        }
Esempio n. 24
0
        private static IEnumerable <string> GraphemeClusters(this string s)
        {
            TextElementEnumerator enumerator = StringInfo.GetTextElementEnumerator(s);

            while (enumerator.MoveNext())
            {
                yield return((string)enumerator.Current);
            }
        }
        private static IEnumerable <string> TextElementCore(string input)
        {
            TextElementEnumerator elementEnumerator = StringInfo.GetTextElementEnumerator(input);

            while (elementEnumerator.MoveNext())
            {
                string textElement = elementEnumerator.GetTextElement();
                yield return(textElement);
            }
        }
Esempio n. 26
0
        public static string[] ToTextElements(string str)
        {
            List <string>         elements = new List <string>();
            TextElementEnumerator textEnum = StringInfo.GetTextElementEnumerator(str);

            while (textEnum.MoveNext())
            {
                elements.Add(textEnum.GetTextElement());
            }
            return(elements.ToArray());
        }
Esempio n. 27
0
 private static string ReverseText(string text)
 {
     TextElementEnumerator enumerator = StringInfo.GetTextElementEnumerator(text);
     List<string> elements = new List<string>();
     while (enumerator.MoveNext())
     {
         elements.Add(enumerator.GetTextElement());
     }
     elements.Reverse();
     return string.Concat(elements);
 }
Esempio n. 28
0
        static void EnumTextElements(string s)
        {
            string output = string.Empty;
            TextElementEnumerator charEnum = StringInfo.GetTextElementEnumerator(s);

            while (charEnum.MoveNext())
            {
                output += string.Format("Character at index{0} is '{1}' {2}", charEnum.ElementIndex, charEnum.GetTextElement(), Environment.NewLine);
            }
            MessageBox.Show(output, "Result of GetTextElementEnumerator");
        }
Esempio n. 29
0
            public override bool TryIteratorStep(out ObjectInstance nextItem)
            {
                if (_iterator.MoveNext())
                {
                    nextItem = new ValueIteratorPosition(_engine, (string)_iterator.Current);
                    return(true);
                }

                nextItem = KeyValueIteratorPosition.Done;
                return(false);
            }
Esempio n. 30
0
        public void Enumerate(string[] expectedElements)
        {
            TextElementEnumerator enumerator = StringInfo.GetTextElementEnumerator(string.Concat(expectedElements));

            for (int i = 0; i < 2; i++)
            {
                int charsProcessedSoFar = 0;

                foreach (string expectedElement in expectedElements)
                {
                    Assert.True(enumerator.MoveNext());
                    Assert.Equal(charsProcessedSoFar, enumerator.ElementIndex);
                    Assert.Equal(expectedElement, enumerator.Current);
                    charsProcessedSoFar += expectedElement.Length;
                }

                Assert.False(enumerator.MoveNext());
                enumerator.Reset();
            }
        }