public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Check two different instance"); try { string str = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH); StringInfo stringInfo1 = new StringInfo(str); StringInfo stringInfo2 = new StringInfo(""); if (stringInfo1.GetHashCode() == stringInfo2.GetHashCode()) { TestLibrary.TestFramework.LogError("003", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; }
public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: The two instances created by the same argument return the same hashcode"); try { string str = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH); StringInfo stringInfo1 = new StringInfo(str); StringInfo stringInfo2 = new StringInfo(str); if (stringInfo1.GetHashCode() != stringInfo2.GetHashCode()) { TestLibrary.TestFramework.LogError("001", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; }
public void String_Set() { string value = s_randomDataGenerator.GetString(-55, false, MinStringLength, MaxStringLength); StringInfo stringInfo = new StringInfo(); stringInfo.String = value; Assert.Equal(value, stringInfo.String); }
public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Call constructor to create an instance with a random string argument"); try { string str = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH); StringInfo stringInfo = new StringInfo(str); if (stringInfo == null) { TestLibrary.TestFramework.LogError("001", "The constructor does not create a new instance"); retVal = false; } if (stringInfo.String != str) { TestLibrary.TestFramework.LogError("002", "The constructor does not work correctly,the str is: " + str); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("003", "Unexpected exception: " + e); retVal = false; } return retVal; }
public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: The two stringinfos reference to one object "); try { string str = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH); StringInfo stringInfo1 = new StringInfo(str); StringInfo stringInfo2 = stringInfo1; if (!stringInfo1.Equals(stringInfo2)) { TestLibrary.TestFramework.LogError("003", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; }
public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Call constructor to create an instance with an empty string argument"); try { string str = string.Empty; StringInfo stringInfo = new StringInfo(str); if (stringInfo == null) { TestLibrary.TestFramework.LogError("004", "The constructor does not create a new instance"); retVal = false; } if (stringInfo.String != string.Empty) { TestLibrary.TestFramework.LogError("005", "The constructor does not work correctly,the str is: " + str); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e); retVal = false; } return retVal; }
public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Call constructor to create an instance"); try { StringInfo stringInfo = new StringInfo(); if (stringInfo == null) { TestLibrary.TestFramework.LogError("001", "The constructor does not create a new instance"); retVal = false; } if (stringInfo.String != string.Empty) { TestLibrary.TestFramework.LogError("002", "The constructor does not work correctly"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("003", "Unexpected exception: " + e); retVal = false; } return retVal; }
public void Equals(StringInfo stringInfo, object value, bool expected) { Assert.Equal(expected, stringInfo.Equals(value)); if (value is StringInfo) { Assert.Equal(expected, stringInfo.GetHashCode().Equals(value.GetHashCode())); } }
public BassControl() { InitializeComponent(); stringInfos = new StringInfo[4]; stringInfos[0] = new StringInfo() { Row = 3, Min = 28, Max = 32, Rect = string3 }; stringInfos[1] = new StringInfo() { Row = 2, Min = 33, Max = 37, Rect = string2 }; stringInfos[2] = new StringInfo() { Row = 1, Min = 38, Max = 42, Rect = string1 }; stringInfos[3] = new StringInfo() { Row = 0, Min = 43, Max = 78, Rect = string0 }; }
public static IEnumerable<object[]> Equals_TestData() { string randomString = s_randomDataGenerator.GetString(-55, false, MinStringLength, MaxStringLength); StringInfo randomStringInfo = new StringInfo(randomString); yield return new object[] { randomStringInfo, new StringInfo(randomString), true }; yield return new object[] { randomStringInfo, randomStringInfo, true }; yield return new object[] { new StringInfo(), new StringInfo(), true }; yield return new object[] { new StringInfo("stringinfo1"), new StringInfo("stringinfo2"), false }; yield return new object[] { new StringInfo("stringinfo1"), "stringinfo1", false }; yield return new object[] { new StringInfo("stringinfo1"), 123, false }; yield return new object[] { new StringInfo("stringinfo1"), null, false }; }
public GuitarControl() { InitializeComponent(); stringInfos = new StringInfo[6]; stringInfos[0] = new StringInfo() { Row = 5, Min = 40, Max = 44, Rect = string5 }; stringInfos[1] = new StringInfo() { Row = 4, Min = 45, Max = 49, Rect = string4 }; stringInfos[2] = new StringInfo() { Row = 3, Min = 50, Max = 54, Rect = string3 }; stringInfos[3] = new StringInfo() { Row = 2, Min = 55, Max = 58, Rect = string2 }; stringInfos[4] = new StringInfo() { Row = 1, Min = 59, Max = 63, Rect = string1 }; stringInfos[5] = new StringInfo() { Row = 0, Min = 64, Max = 90, Rect = string0 }; }
public void NegativeTest() { string s = "Some String"; StringInfo si = new StringInfo(s); StringInfo siEmpty = new StringInfo(""); Assert.Throws<ArgumentOutOfRangeException>(() => si.SubstringByTextElements(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => si.SubstringByTextElements(s.Length + 1)); Assert.Throws<ArgumentOutOfRangeException>(() => siEmpty.SubstringByTextElements(0)); Assert.Throws<ArgumentOutOfRangeException>(() => si.SubstringByTextElements(-1, 1)); Assert.Throws<ArgumentOutOfRangeException>(() => si.SubstringByTextElements(s.Length + 1, 1)); Assert.Throws<ArgumentOutOfRangeException>(() => siEmpty.SubstringByTextElements(0, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => si.SubstringByTextElements(0, s.Length + 1)); }
private static void RunStringInfo() { // string info var stringInfoItelator = StringInfo.GetTextElementEnumerator("👨👩👧👧"); while (stringInfoItelator.MoveNext()) { Console.WriteLine(stringInfoItelator.Current); } var stringInfo = new StringInfo("👨👩👧👧"); Console.WriteLine(stringInfo.LengthInTextElements); // same as Enumerator for (var i = 0; i < stringInfo.LengthInTextElements; i++) { Console.WriteLine(stringInfo.SubstringByTextElements(i, 1)); } }
static void SentimentAnalysisExample(TextAnalyticsClient client, string inputText) { DocumentSentiment documentSentiment = client.AnalyzeSentiment(inputText); Console.WriteLine($"Document sentiment: {documentSentiment.Sentiment}\n"); var si = new StringInfo(inputText); foreach (var sentence in documentSentiment.Sentences) { Console.WriteLine($"\tSentence [length {sentence.GraphemeLength}]"); Console.WriteLine($"\tText: \"{si.SubstringByTextElements(sentence.GraphemeOffset, sentence.GraphemeLength)}\""); Console.WriteLine($"\tSentence sentiment: {sentence.Sentiment}"); Console.WriteLine($"\tPositive score: {sentence.ConfidenceScores.Positive:0.00}"); Console.WriteLine($"\tNegative score: {sentence.ConfidenceScores.Negative:0.00}"); Console.WriteLine($"\tNeutral score: {sentence.ConfidenceScores.Neutral:0.00}\n"); } }
public string SetType(string header) { string type = ""; if (StringInfo.GetNextTextElement(header, 0) == "T") { type = "Twitter"; } if (StringInfo.GetNextTextElement(header, 0) == "S") { type = "SMS"; } if (StringInfo.GetNextTextElement(header, 0) == "E") { type = "Email"; } return(type); }
/// <summary> /// Gets the next text element at the given offset. /// </summary> /// <param name="offset">The offset, in characters, within the buffer to start at.</param> /// <returns>The next text element at that position.</returns> string _nextTextElement(int offset) { while (true) { // Only accept the element if it isn't at the end of the buffer. This ensures we get the // whole element, even if it extends into the next read. string elem = StringInfo.GetNextTextElement(_buffer, _bufferPos + offset); if (_bufferPos + offset + elem.Length < _buffer.Length) { return(elem); } // If at EOF, just return what we read. if (!_extendBuffer()) { return(elem); } } }
public static DocumentSentiment GetSentiment(string input) { var client = new TextAnalyticsClient(endpoint, credentials); DocumentSentiment documentSentiment = client.AnalyzeSentiment(input); Console.WriteLine($"Document sentiment: {documentSentiment.Sentiment}\n"); var si = new StringInfo(input); foreach (var sentence in documentSentiment.Sentences) { Console.WriteLine($"\tSentence [length {sentence.GraphemeLength}]"); Console.WriteLine($"\tText: \"{si.SubstringByTextElements(sentence.GraphemeOffset, sentence.GraphemeLength)}\""); Console.WriteLine($"\tSentence sentiment: {sentence.Sentiment}"); Console.WriteLine($"\tPositive score: {sentence.ConfidenceScores.Positive:0.00}"); Console.WriteLine($"\tNegative score: {sentence.ConfidenceScores.Negative:0.00}"); Console.WriteLine($"\tNeutral score: {sentence.ConfidenceScores.Neutral:0.00}\n"); } return documentSentiment; }
public static string CapitalizeFirstLetter(this string s, CultureInfo ci = null) { var si = new StringInfo(s); if (ci == null) { ci = CultureInfo.CurrentCulture; } if (si.LengthInTextElements > 0) { s = si.SubstringByTextElements(0, 1).ToUpper(ci); } if (si.LengthInTextElements > 1) { s += si.SubstringByTextElements(1); } return(s); }
public void Solve() { int movesSoFar = 0; var sinf = new List <List <StringInfo> >(); foreach (var s in Strings) { var thisinf = new List <StringInfo>(); char p = '0'; StringInfo lastinf = new StringInfo(); for (int i = 0; i < s.Length; i++) { if (s[i] != p) { lastinf = new StringInfo(s[i], 1); thisinf.Add(lastinf); } else { lastinf.Count++; } p = s[i]; } sinf.Add(thisinf); } var c = sinf.First().Count; if (sinf.Any(x => x.Count != c)) { return; } int pos = 0; while (pos < c) { if (sinf.Any(x => x[pos].Letter != sinf.First()[pos].Letter)) { return; } movesSoFar += GetNumberOfMoves(sinf.Select(x => x[pos].Count)); pos++; } Moves = movesSoFar; }
/// <summary> /// Adds a character mapping to translate from source to object /// </summary> /// <param name="mapping">The text element, or range of text elements to map.</param> /// <param name="code">The code of the mapping.</param> /// <exception cref="ArgumentException">System.ArgumentException</exception> /// <exception cref="ArgumentNullException"></exception> public void Map(string mapping, int code) { // the default encoding cannot be changed if (_currentMap == _maps.First().Value) { return; } if (string.IsNullOrEmpty(mapping)) { throw new ArgumentNullException(); } var stringInfo = StringInfo.ParseCombiningCharacters(mapping); if (stringInfo.Length > 1) { if (stringInfo.Length > 2) { throw new ArgumentException(mapping); } var first = char.ConvertToUtf32(mapping, stringInfo.First()); var last = char.ConvertToUtf32(mapping, stringInfo.Last()); if (first > last) { throw new ArgumentException(mapping); } while (first <= last) { _currentMap[first++] = code++; } } else { if (mapping.Length > 1) { throw new ArgumentException(mapping); } _currentMap[char.ConvertToUtf32(mapping, 0)] = code; } }
private bool ValidateString(JSchema schema, string value) { if (!TestType(schema, JSchemaType.String, value)) { return(false); } if (schema.MaximumLength != null || schema.MinimumLength != null) { // want to test the character length and ignore unicode surrogates StringInfo stringInfo = new StringInfo(value); int textLength = stringInfo.LengthInTextElements; if (schema.MaximumLength != null && textLength > schema.MaximumLength) { RaiseError("String '{0}' exceeds maximum length of {1}.".FormatWith(CultureInfo.InvariantCulture, value, schema.MaximumLength), ErrorType.MaximumLength, schema, value, null); } if (schema.MinimumLength != null && textLength < schema.MinimumLength) { RaiseError("String '{0}' is less than minimum length of {1}.".FormatWith(CultureInfo.InvariantCulture, value, schema.MinimumLength), ErrorType.MinimumLength, schema, value, null); } } if (schema.Pattern != null) { if (!Regex.IsMatch(value, schema.Pattern)) { RaiseError("String '{0}' does not match regex pattern '{1}'.".FormatWith(CultureInfo.InvariantCulture, value, schema.Pattern), ErrorType.Pattern, schema, value, null); } } if (schema.Format != null) { bool valid = ValidateFormat(schema.Format, value); if (!valid) { RaiseError("String '{0}' does not validate against format '{1}'.".FormatWith(CultureInfo.InvariantCulture, value, schema.Format), ErrorType.Format, schema, value, null); } } return(true); }
public static void EnumerateTextElements(string str) { // Get the Enumerator. TextElementEnumerator teEnum = null; // Parse the string using the ParseCombiningCharacters method. Console.WriteLine("\nParsing with ParseCombiningCharacters:"); int[] teIndices = StringInfo.ParseCombiningCharacters(str); for (int i = 0; i < teIndices.Length; i++) { if (i < teIndices.Length - 1) { Console.WriteLine("Text Element {0} ({1}..{2})= {3}", i, teIndices[i], teIndices[i + 1] - 1, ShowHexValues(str.Substring(teIndices[i], teIndices[i + 1] - teIndices[i]))); } else { Console.WriteLine("Text Element {0} ({1}..{2})= {3}", i, teIndices[i], str.Length - 1, ShowHexValues(str.Substring(teIndices[i]))); } } Console.WriteLine(); // Parse the string with the GetTextElementEnumerator method. Console.WriteLine("Parsing with TextElementEnumerator:"); teEnum = StringInfo.GetTextElementEnumerator(str); int teCount = -1; while (teEnum.MoveNext()) { // Displays the current element. // Both GetTextElement() and Current retrieve the current // text element. The latter returns it as an Object. teCount++; Console.WriteLine("Text Element {0} ({1}..{2})= {3}", teCount, teEnum.ElementIndex, teEnum.ElementIndex + teEnum.GetTextElement().Length - 1, ShowHexValues((string)(teEnum.Current))); } }
void PrintTextElementCount(ustring us, string s, int consoleWidth, int runeCount, int stringCount, int txtElementCount) { Assert.AreEqual(us.ToString(), s); Assert.AreEqual(s, us.ToString()); Assert.AreEqual(consoleWidth, us.ConsoleWidth); Assert.AreEqual(runeCount, us.RuneCount); Assert.AreEqual(stringCount, s.Length); TextElementEnumerator enumerator = StringInfo.GetTextElementEnumerator(s); int textElementCount = 0; while (enumerator.MoveNext()) { textElementCount++; // For versions prior to Net5.0 the StringInfo class might handle some grapheme clusters incorrectly. } Assert.AreEqual(txtElementCount, textElementCount); }
public static void Main(string[] args) { string s1 = "abcde"; Console.WriteLine(s1.Length); //サロゲートペアを含む文字列。本来6文字 string s2 = "𩸽(ほっけ)"; //サロゲートペアを認識できず、7文字になってしまう Console.WriteLine("Length:" + s2.Length); //StringInfoクラスのLengthInTextElementsプロパティ StringInfo strInfo = new StringInfo(s2); //正しく6文字になる Console.WriteLine("StringInfo.LengthInTextElements:" + strInfo.LengthInTextElements); Console.ReadKey(); }
static void SentimentAnalysisExample(TextAnalyticsClient client) { string inputText = "I had the best day of my life. I wish you were there with me."; DocumentSentiment documentSentiment = client.AnalyzeSentiment(inputText); Console.WriteLine($"Document sentiment: {documentSentiment.Sentiment}\n"); var si = new StringInfo(inputText); foreach (var sentence in documentSentiment.Sentences) { Console.WriteLine($"\tSentence [offset {sentence.Offset}, length {sentence.Length}]"); Console.WriteLine($"\tText: \"{si.SubstringByTextElements(sentence.Offset, sentence.Length)}\""); Console.WriteLine($"\tSentence sentiment: {sentence.Sentiment}"); Console.WriteLine($"\tPositive score: {sentence.SentimentScores.Positive:0.00}"); Console.WriteLine($"\tNegative score: {sentence.SentimentScores.Negative:0.00}"); Console.WriteLine($"\tNeutral score: {sentence.SentimentScores.Neutral:0.00}\n"); } }
public static StringInfo InsertByTextElements(this StringInfo str, int offset, string insertStr) { //Tue 20-Aug-19 11:32am metadataconsulting.ca - replaceat index > string.len return orginal string if (offset > str.LengthInTextElements) { return(str); } if (string.IsNullOrEmpty(str.String)) { return(new StringInfo(insertStr)); } return(new StringInfo(string.Concat( str.SubstringByTextElements(0, offset), insertStr, str.LengthInTextElements - offset > 0 ? str.SubstringByTextElements(offset, str.LengthInTextElements - offset) : "" ))); }
private void button1_Click(object sender, EventArgs e) { int code = 0; string str1 = richTextBox1.Text; string str2 = ""; StringInfo ss = new StringInfo(str1); int m = ss.LengthInTextElements;//字符长度 string word = ""; for (int i = 0; i < m; i++) { word = ss.SubstringByTextElements(i, 1); code = Char.ConvertToUtf32(word, 0); str2 = str2 + "\\" + Convert.ToString(code, 16); } richTextBox2.Text = str2; }
public static Uri BuildUri(string string2) { var result = string.Empty; var i = 0; var textEnumerator = StringInfo.GetTextElementEnumerator(string2); var cont = textEnumerator.MoveNext(); while (cont) { var text = textEnumerator.GetTextElement(); var bytes = Encoding.BigEndianUnicode.GetBytes(text); var bytesStr = ConvertToHexString(bytes); result += bytesStr; cont = textEnumerator.MoveNext(); } return(new Uri(string.Format("/Assets/Emoji/Separated/{0}.png", result), UriKind.Relative)); }
/// <summary> /// Separates emoji and special characters from a complex string. /// </summary> /// <param name="inp">The input string.</param> /// <returns>The enumerable of emojis, characters, and special characters.</returns> public IEnumerable <string> SeparateEmojiAndSpecialChars(string inp) { int lstart = 0; for (int i = 0; i < inp.Length; i++) { if (inp[i] == ':') { for (int x = i + 1; x < inp.Length; x++) { if (inp[x] == ' ') { break; } else if (inp[x] == ':') { string split = inp.Substring(i + 1, x - (i + 1)); if (!IsEmojiName(split)) { InvalidEmoji.Add(split); break; } string pre_pieces = inp.Substring(lstart, i - lstart); foreach (string stx in StringInfo.GetTextElementEnumerator(pre_pieces).AsEnumerable <string>()) { yield return(stx); } yield return(":" + split + ":"); i = x; lstart = x + 1; break; } } } } string final_pieces = inp.Substring(lstart); foreach (string stx in StringInfo.GetTextElementEnumerator(final_pieces).AsEnumerable <string>()) { yield return(stx); } }
public static void UpdateGroup(string GroupId, string GroupName, string Locale) { StringInfo nameInfo = effority.Ealo.Controller.GetStringByQualifierAndStringName(GroupQualifier, GroupId, Locale, false); if (!string.IsNullOrEmpty(Locale)) { if (!string.IsNullOrEmpty(GroupName)) { effority.Ealo.Controller.UpdateStringByQualiferAndStringName(GroupQualifier, GroupId, GroupName, Locale, true); } else { if (nameInfo != null) { effority.Ealo.Controller.DeleteByQualifierAndStringNameAndLocale(GroupQualifier, GroupId, Locale); } } } }
private static int[] CodePoints(string s) { if (!s.IsNormalized()) { s = s.Normalize(); } var chars = new List <int>((s.Length * 3) / 2); var ee = StringInfo.GetTextElementEnumerator(s); while (ee.MoveNext()) { var e = ee.GetTextElement(); chars.Add(char.ConvertToUtf32(e, 0)); } return(chars.ToArray()); }
public StringInfo GetStringInfo(string str) { StringInfo ret; if (this.stringLookup.TryGetValue(str, out ret) == true) { return(ret); } int size = str.Length * BytesPerChar + BytePadding; ret = new StringInfo(this.storedStrings.Count, str, totalSize, size); this.totalSize += size; this.storedStrings.Add(ret); this.stringLookup.Add(str, ret); return(ret); }
public static string SanitizeEmojiText(string message) { if (!StringHasSurrogates(message)) { return(message); } var sb = new StringBuilder(); var charEnum = StringInfo.GetTextElementEnumerator(message); while (charEnum.MoveNext()) { var text = charEnum.GetTextElement(); if (text.Length == 1) { sb.AppendFormat(text); } } return(sb.ToString()); }
public void NegTest2() { String myString = "\uD800\uDC00\u0061\u0300\u00C6"; // Creates and initializes a TextElementEnumerator for myString. TextElementEnumerator myTEE = StringInfo.GetTextElementEnumerator(myString); myTEE.Reset(); string actualValue = null; while (myTEE.MoveNext()) { actualValue = myTEE.Current.ToString(); } Assert.Throws <InvalidOperationException>(() => { actualValue = myTEE.Current.ToString(); }); }
/* * find patterns based on a fixed size only window * returns only patterns bigger than 1, or an empty list if none * * if inputStr is coming from the wire/internet, we should check if its well-formed, https://docs.microsoft.com/en-us/dotnet/standard/base-types/character-encoding-introduction * * Some inspirational material * https://docs.microsoft.com/en-us/archive/msdn-magazine/2018/january/csharp-all-about-span-exploring-a-new-net-mainstay * https://codereview.stackexchange.com/questions/194716/substring-vs-split-performance-test * https://www.stevejgordon.co.uk/an-introduction-to-optimising-code-using-span-t * https://www.meziantou.net/split-a-string-into-lines-without-allocation.htm */ public static List <KeyValuePair <string, int> > GetPatternList(string inputString, int patternLength) { // basic validation: // input string should not be empty // patternLength should be greater than 0 and less/equal than inputString.Length if (string.IsNullOrEmpty(inputString)) { throw new ArgumentException("Should not be null or empty", "inputString"); } if (patternLength <= 0) { throw new ArgumentException("Should be greater than 0", "patternLength"); } if (patternLength > inputString.Length) { throw new ArgumentException("Should be less or equal than inputString.Length", "patternLength"); } var slicesDict = new Dictionary <string, int>(); var resultList = new List <KeyValuePair <string, int> >(); var inputStringInfo = new StringInfo(inputString); //Dirty-fix to UTF8 strings var slice = new StringBuilder(inputStringInfo.LengthInTextElements); for (int i = 0; i < (inputStringInfo.LengthInTextElements - patternLength) + 1; i++) { slice.Append(inputStringInfo.SubstringByTextElements(i, patternLength)); if (slicesDict.TryGetValue(slice.ToString(), out int patternCount)) { slicesDict[slice.ToString()] = patternCount + 1; } else { slicesDict.Add(slice.ToString(), 1); } slice.Clear(); } resultList = slicesDict.Where(p => p.Value > 1).ToList(); return(resultList); }
/// <summary> /// Provides validation for the keyword. /// </summary> /// <param name="context">Contextual details for the validation process.</param> public void Validate(ValidationContext context) { context.EnterKeyword(Name); if (context.LocalInstance.ValueKind != JsonValueKind.String) { context.WrongValueKind(context.LocalInstance.ValueKind); context.IsValid = true; return; } var length = new StringInfo(context.LocalInstance.GetString()).LengthInTextElements; context.IsValid = Value <= length; if (!context.IsValid) { context.Message = $"Value is not longer than or equal to {Value} characters"; } context.ExitKeyword(Name, context.IsValid); }
/// <summary> /// Calculates the number of bytes produced by encoding the string. /// </summary> /// <param name="s">The string to encode</param> public override int GetByteCount(string s) { int numbytes = 0; var textEnumerator = StringInfo.GetTextElementEnumerator(s); while (textEnumerator.MoveNext()) { var elem = textEnumerator.GetTextElement(); if (_currentMap.ContainsKey(elem)) { numbytes += ((long)_currentMap[elem]).Size(); } else { numbytes += UTF8.GetByteCount(elem); } } return(numbytes); }
public static IEnumerable <object[]> Equals_TestData() { string randomString = s_RandomDataGenerator.GetString(-55, false, MinStringLength, MaxStringLength); StringInfo randomStringInfo = new StringInfo(randomString); yield return(new object[] { randomStringInfo, new StringInfo(randomString), true }); yield return(new object[] { randomStringInfo, randomStringInfo, true }); yield return(new object[] { new StringInfo(), new StringInfo(), true }); yield return(new object[] { new StringInfo("stringinfo1"), new StringInfo("stringinfo2"), false }); yield return(new object[] { new StringInfo("stringinfo1"), "stringinfo1", false }); yield return(new object[] { new StringInfo("stringinfo1"), 123, false }); yield return(new object[] { new StringInfo("stringinfo1"), null, false }); }
/// <inheritdoc /> public bool Task3(string phrase) { if (phrase.Length == 0) { return(false); } string reversedPhrase; StringBuilder sb = new StringBuilder(); var enumerator = StringInfo.GetTextElementEnumerator(phrase); while (enumerator.MoveNext()) { sb.Insert(0, (string)enumerator.Current); } reversedPhrase = sb.ToString(); // very incomplete list of symbols! var symbolsToSkip = new String[] { " ", "-", ",", "." }; var enumeratorL = StringInfo.GetTextElementEnumerator(phrase); var enumeratorR = StringInfo.GetTextElementEnumerator(reversedPhrase); while (enumeratorL.MoveNext() && enumeratorR.MoveNext()) { while (symbolsToSkip.Contains((string)enumeratorL.Current) && enumeratorL.MoveNext()) { ; } while (symbolsToSkip.Contains((string)enumeratorR.Current) && enumeratorR.MoveNext()) { ; } if (((string)enumeratorL.Current).ToLower() != ((string)enumeratorR.Current).ToLower()) { return(false); } } return(true); }
internal static bool ValidateString(SchemaScope scope, JSchema schema, string value) { if (!TestType(scope, schema, JSchemaType.String, value)) { return(false); } if (schema.MaximumLength != null || schema.MinimumLength != null) { // want to test the character length and ignore unicode surrogates StringInfo stringInfo = new StringInfo(value); int textLength = stringInfo.LengthInTextElements; if (schema.MaximumLength != null && textLength > schema.MaximumLength) { scope.RaiseError($"String '{value}' exceeds maximum length of {schema.MaximumLength}.", ErrorType.MaximumLength, schema, value, null); } if (schema.MinimumLength != null && textLength < schema.MinimumLength) { scope.RaiseError($"String '{value}' is less than minimum length of {schema.MinimumLength}.", ErrorType.MinimumLength, schema, value, null); } } if (schema.Pattern != null) { if (schema.TryGetPatternRegex( #if !(NET35 || NET40) scope.Context.Validator.RegexMatchTimeout, #endif out Regex regex, out string errorMessage)) { if (!RegexHelpers.IsMatch(regex, schema.Pattern, value)) { scope.RaiseError($"String '{value}' does not match regex pattern '{schema.Pattern}'.", ErrorType.Pattern, schema, value, null); } } else { scope.RaiseError($"Could not validate string with regex pattern '{schema.Pattern}'. There was an error parsing the regex: {errorMessage}", ErrorType.Pattern, schema, value, null); } }
private string computeOther() { var sb = new StringBuilder(); int[] graphemeIndices = StringInfo.ParseCombiningCharacters(_name); for (int i = graphemeIndices.Length - 1; i >= 0; i--) { string c = StringInfo.GetNextTextElement(_name, i); if (UnicodeLookup.MirroredBrackets.ContainsKey(c)) { sb.Append(UnicodeLookup.MirroredBrackets[c]); } else { sb.Append(c); } } return(sb.ToString()); }
public SentiText(SentimentIntensityAnalyzer az, string text) { Az = az; Text = text; // convert emoji to word equivalents // are there any ? var match = Az.SubsubstituteEmoji.Match(text); if (match.Success) { var itr = StringInfo.GetTextElementEnumerator(text); var sb = new StringBuilder(); while (itr.MoveNext()) { var el = itr.GetTextElement(); // just skip if can't find if (az.Emojicon.TryGetValue(el, out var desc)) { sb.Append(' '); sb.Append(desc); sb.Append(' '); } else { sb.Append(el); } } ExpandedText = sb.ToString(); } else { ExpandedText = text; } StripWrapingPunctuation(); }
private bool moveToNextID() { if(++currentIdIdx > ids.Length - 1) { currentIdIdx = 0; currentLanguageIdx++; if(currentLanguageIdx < languages.Length) { StringTable.loadFile(languages[currentLanguageIdx]); } else{ currentLanguageIdx = 0; return false; } } info = ids[currentIdIdx]; language = languages[currentLanguageIdx]; return true; }
public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: The string property in stringinfo object is an empty string argument"); try { string str = string.Empty; StringInfo stringInfo = new StringInfo(str); if (stringInfo.String != string.Empty) { TestLibrary.TestFramework.LogError("003", "The constructor does not work correctly,the str is: " + str); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; }
public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: The string is a null reference"); try { string str = null; StringInfo stringInfo = new StringInfo(str); TestLibrary.TestFramework.LogError("101", "The ArgumentNullException was not thrown as expected"); retVal = false; } catch (ArgumentNullException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; }
public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Using default constructor to create two equal instance"); try { StringInfo stringInfo1 = new StringInfo(); StringInfo stringInfo2 = new StringInfo(); if (!stringInfo1.Equals(stringInfo2)) { TestLibrary.TestFramework.LogError("005", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e); retVal = false; } return retVal; }
public bool PosTest7() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest7: The argument is value type"); try { StringInfo stringInfo1 = new StringInfo("123"); int i = 123; if (stringInfo1.Equals(i)) { TestLibrary.TestFramework.LogError("013", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("014", "Unexpected exception: " + e); retVal = false; } return retVal; }
string Decrypt(StringInfo info) { if (info.decrypted == null) info.decrypted = decrypter.Decrypt(info.stringId); return info.decrypted; }
public void Ctor_Empty() { StringInfo stringInfo = new StringInfo(); Assert.Equal(string.Empty, stringInfo.String); Assert.Equal(0, stringInfo.LengthInTextElements); }
public void Ctor_String(string value) { var stringInfo = new StringInfo(value); Assert.Equal(value, stringInfo.String); }
public void Ctor_String(string value, int lengthInTextElements) { var stringInfo = new StringInfo(value); Assert.Same(value, stringInfo.String); Assert.Equal(lengthInTextElements, stringInfo.LengthInTextElements); }
public void String_Set(string value) { StringInfo stringInfo = new StringInfo(); stringInfo.String = value; Assert.Same(value, stringInfo.String); }
private bool VerificationHelper(string str, int expected, string errorno) { bool retVal = true; StringInfo stringInfo = new StringInfo(str); int result = stringInfo.LengthInTextElements; if (result != expected) { TestLibrary.TestFramework.LogError(errorno, "The result is not the value as expected,The actual is: " + result + ", the desire is: " + expected); retVal = false; } return retVal; }
public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Set the property with a random string value"); try { string str = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH); StringInfo stringInfo = new StringInfo(); stringInfo.String = str; if (stringInfo.String != str) { TestLibrary.TestFramework.LogError("007", "The constructor does not work correctly,the str is: " + str); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); retVal = false; } return retVal; }
public bool PosTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest5: Compare with a different kind of type"); try { StringInfo stringInfo1 = new StringInfo("stringinfo1"); string str = "stringinfo1"; if (stringInfo1.Equals(str)) { TestLibrary.TestFramework.LogError("009", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e); retVal = false; } return retVal; }
public bool PosTest6() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest6: The argument is a null reference"); try { StringInfo stringInfo1 = new StringInfo("stringinfo1"); object ob = null; if (stringInfo1.Equals(ob)) { TestLibrary.TestFramework.LogError("011", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("012", "Unexpected exception: " + e); retVal = false; } return retVal; }
public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Compare two instance with different string value"); try { StringInfo stringInfo1 = new StringInfo("stringinfo1"); StringInfo stringInfo2 = new StringInfo("stringinfo2"); if (stringInfo1.Equals(stringInfo2)) { TestLibrary.TestFramework.LogError("007", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); retVal = false; } return retVal; }
/// <summary> /// Class constructor /// </summary> /// <param name="languageID">Language ID</param> /// <param name="male">True if string is masculine</param> /// <param name="val">String</param> public ExoLocString(uint languageID, bool male, string val) { StringInfo info = new StringInfo(); info.LanguageID = languageID; info.Male = male; info.Text = val; strings = new ArrayList(); strings.Add(info); }
public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Call constructor to create an instance with a string of white space"); try { string str = " "; StringInfo stringInfo = new StringInfo(str); if (stringInfo == null) { TestLibrary.TestFramework.LogError("007", "The constructor does not create a new instance"); retVal = false; } if (stringInfo.String != " ") { TestLibrary.TestFramework.LogError("008", "The constructor does not work correctly,the str is: " + str); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("009", "Unexpected exception: " + e); retVal = false; } return retVal; }
/// <summary> /// Class constructor to create an ExoLocString from the GFF /// file's raw data. /// </summary> /// <param name="buffer">Byte array containing the raw data</param> /// <param name="offset">Offset to the data</param> public ExoLocString(Byte[] buffer, int offset) { strings = new ArrayList(); // Get the total size in bytes of the ExoLocString. uint size = BitConverter.ToUInt32(buffer, offset); offset += 4; // Get the dialog.tlk StrRef, if it is valid (not -1) then // we are doine. strRef = BitConverter.ToUInt32(buffer, offset); offset += 4; if (0xffffffff != strRef) return; // Get the number of sub-strings in the ExoLocString and // build StringInfo objects for each of them, adding them // to our collection. uint count = BitConverter.ToUInt32(buffer, offset); offset += 4; for (int i = 0; i < count; i++) { // Get the sub-string's languageID and length. uint stringID = BitConverter.ToUInt32(buffer, offset); offset += 4; uint length = BitConverter.ToUInt32(buffer, offset); offset += 4; // Create the string info object, and fill it in with the // proper data. StringInfo info = new StringInfo(); info.LanguageID = stringID / 2; info.Male = 0 == stringID % 2; info.Text = RawGffData.DeserializeString(buffer, offset, (int) length); offset += (int) length; strings.Add(info); } }