public static void TestEquals() { StringBuilder sb1 = new StringBuilder("Hello"); StringBuilder sb2 = new StringBuilder("HelloX"); bool b; b = sb1.Equals(sb1); Assert.True(b); b = sb1.Equals(sb2); Assert.False(b); }
public bool RotateString_firstattempt(string a, string b) { if (a?.Length != b?.Length) { return(false); } if (string.IsNullOrWhiteSpace(a) && string.IsNullOrWhiteSpace(b)) { return(true); } var sb = new StringBuilder(a); char fc; for (int i = 0; i < a.Length; i++) { fc = sb[0]; sb.Remove(0, 1); sb.Append(fc); if (sb.Equals(b)) { return(true); } } return(false); }
public void Method(Func <string> func) { var sb1 = new StringBuilder("hey"); var sb2 = new StringBuilder("hey"); if (sb1 == sb2) { } else { if (sb1.Equals(sb2)) { } } var s1 = "hi"; var s2 = "hi"; if (s1 == s2) { } if (s1.Equals(s2)) { } var me = new Teaser(); me.Foo(); Bar <StringBuilder>(); UnCanny(); }
public void CheckNotEquals() { var sb = new StringBuilder("Hello World!"); var equals = sb.Equals("Hello World1".AsSpan()); Assert.That(equals, Is.Not.True); }
public void CheckEquals() { var sb = new StringBuilder("Hello World"); var equals = sb.Equals("Hello World".AsSpan()); Assert.That(equals); }
static void Main(string[] args) { Area a1 = new Area(5, 10); Area a2 = new Area(10, 5); Console.WriteLine(a1.Equals(a2)); // prawda Console.WriteLine(a1 == a2); // prawda // int x = 5, y = 5; Console.WriteLine(x == y); // prawda (dzięki zasadom równości wartościowej) var dt1 = new DateTimeOffset(2010, 1, 1, 1, 1, 1, TimeSpan.FromHours(8)); var dt2 = new DateTimeOffset(2010, 1, 1, 2, 1, 1, TimeSpan.FromHours(9)); Console.WriteLine(dt1 == dt2); // True Uri uri1 = new Uri("http://www.linqpad.net"); Uri uri2 = new Uri("http://www.linqpad.net"); Console.WriteLine(uri1 == uri2); // prawda double z = double.NaN; Console.WriteLine(z == z); // fałsz Console.WriteLine(z.Equals(z)); // prawda var sb1 = new StringBuilder("foo"); var sb2 = new StringBuilder("foo"); Console.WriteLine(sb1 == sb2); // fałsz (równość referencyjna) Console.WriteLine(sb1.Equals(sb2)); // prawda (równość wartościowa) Console.ReadKey(); }
static void Main(string[] args) { string str = "hello"; string s = null; string st = s ?? string.Empty; Console.WriteLine(st.Length); StringBuilder stringBuilder1 = new StringBuilder("hello"); StringBuilder stringBuilder2 = new StringBuilder("hello"); //Console.WriteLine(str == stringBuilder1); Console.WriteLine(str.Equals(stringBuilder1)); //http://Google.ru Console.WriteLine(stringBuilder1.Equals(stringBuilder2)); Console.WriteLine((double)0.1f); string str1 = null; string str2 = "1"; Console.WriteLine(Equals(str1, str2)); Console.ReadKey(); }
//Stdcall private static void TestMethod_SLPStr_In() { TestFramework.BeginScenario("StdCall,LPStr,In"); try { StringBuilder sb = GetInvalidString(); string rstr = SLPStr_In(sb.ToString()); //Check the return value and the parameter. StringBuilder sbTemp = GetInvalidString(); if (!Compare(sbTemp.ToString(), rstr)) { Fails++; TestFramework.LogError("015", "TestMethod_SLPStr_In:The Return value is wrong."); } if (!sb.Equals(sbTemp)) { Fails++; TestFramework.LogError("016", "TestMethod_SLPStr_In:The Parameter value is wrong."); } } catch (Exception e) { Fails++; TestFramework.LogError("e08", "TestMethod_SLPStr_In:Unexpected Exception Occured:" + e.ToString()); } }
public static bool ArePolindromes(StringBuilder result) { StringBuilder trimmedResult = new StringBuilder(); for (int i = 0; i < result.Length; i++) { if (char.IsLetter(result[i])) { trimmedResult.Append(char.ToLower(result[i])); } } StringBuilder reversedTrimmedResult = new StringBuilder(); for (int i = result.Length - 1; i >= 0; i--) { if (char.IsLetter(result[i])) { reversedTrimmedResult.Append(char.ToLower(result[i])); } } if (trimmedResult.Equals(reversedTrimmedResult)) { return(true); } return(false); }
protected virtual IEnumerable <string> GetTerms(string text) { var term = new StringBuilder(); var terms = new List <string>(); foreach (char ch in text) { if (char.IsLetter(ch)) { term.Append(ch); } else if (char.IsDigit(ch)) { term.Append(ch); } else { if (!term.Equals("")) { terms.Add(term.ToString()); } term.Clear(); } } if (!term.ToString().Equals("")) { terms.Add(term.ToString()); } return(terms); }
public bool Equals(FilterInfoKey other) { if (StringValue != null) { return(string.Equals(StringValue, other.StringValue, StringComparison.Ordinal)); } if (_stringBuffer != null && other._stringBuffer != null) { // StringBuilder.Equals only works when StringBuilder.Capacity is the same if (_stringBuffer.Capacity != other._stringBuffer.Capacity) { if (_stringBuffer.Length != other._stringBuffer.Length) { return(false); } for (int x = 0; x < _stringBuffer.Length; ++x) { if (_stringBuffer[x] != other._stringBuffer[x]) { return(false); } } return(true); } return(_stringBuffer.Equals(other._stringBuffer)); } return(ReferenceEquals(_stringBuffer, other._stringBuffer) && ReferenceEquals(StringValue, other.StringValue)); }
/// <summary> /// utility method to print the given array in a way that looks nice :D /// </summary> /// <param name="arr"></param> /// <returns></returns> static string PrintArray(int[,] arr) { StringBuilder ret = new StringBuilder(); ret.AppendLine(arr.Length == 0 ? "[[]]" : "["); if (ret.Equals("[[]]")) { return(ret.ToString()); } for (int i = 0; i < arr.GetLength(0); i++) { ret.Append(" ["); for (int j = 0; j < arr.GetLength(1); j++) { ret.Append(arr[i, j] + (j == arr.GetLength(1) - 1 ? string.Empty : ", ")); } if (i == arr.GetLength(0) - 1) { ret.AppendLine("]"); } else { ret.AppendLine("],"); } } ret.Append("]"); return(ret.ToString()); }
private static void TestMethod_CLPStr_In() { TestFramework.BeginScenario("Cdecl,LPStr,In"); try { StringBuilder sb = GetInvalidString(); string str = sb.ToString(); string rstr = CLPStr_In(str); //Check the return value and the parameter. StringBuilder sbTemp = GetInvalidString(); if (!Compare(str, rstr)) { Fails++; TestFramework.LogError("001", "TestMethod_CLPStr_In"); } if (!sb.Equals(sbTemp)) { Fails++; TestFramework.LogError("002", "TestMethod_CLPStr_In"); } } catch (Exception e) { Fails++; TestFramework.LogError("e01", "TestMethod_CLPStr_In:Unexpected Exception Occured:" + e.ToString()); } }
private void OnDocumentMouseUp(object sender, HtmlElementEventArgs e) { if (!IsEditable && !String.IsNullOrWhiteSpace(m_CurrentHRef)) { var href = new StringBuilder(m_CurrentHRef).ToString(); m_CurrentHRef = ""; // Verify that the mouse hasn't moved var element = this.WebBrowser.Document.GetElementFromPoint(e.ClientMousePosition); if (element == null) { return; } if (!href.Equals(element.GetAttribute("href"))) { return; } if (HtmlNavigation != null) { HtmlNavigation(this, new MSDN.Html.Editor.HtmlNavigationEventArgs(href)); } } }
private StringBuilder CheckTextThousands(StringBuilder phrase) { if (digits.Count.Equals(2)) { if (ParamThousands > 3 && ParamThousands < 7 && !phrase.Equals("")) { if (Int32.Parse(digits[0].ToString()) > 1) { if (Int32.Parse(digits[1].ToString()) < 100 && Int32.Parse(digits[1].ToString()) > 0) { phrase.Append(" mil e"); } else if (Int32.Parse(digits[1].ToString()) >= 100 || Int32.Parse(digits[1].ToString()) == 0) { phrase.Append(" mil"); } } else if (Int32.Parse(digits[0].ToString()) == 1) { if (Int32.Parse(digits[1].ToString()) < 100 && Int32.Parse(digits[1].ToString()) > 0) { phrase = new StringBuilder(" mil e"); } else if (Int32.Parse(digits[1].ToString()) >= 100 || Int32.Parse(digits[1].ToString()) == 0) { phrase = new StringBuilder("mil"); } } } } return(phrase); }
public void UpdateSequence(int mutationId, Sequence sequenceForReference) { var sequenceToUpdate = DictionaryofSequences[mutationId]; for (int i = 0; i < sequenceToUpdate.Combinations.Length; i++) { var combinationReference = sequenceForReference.Combinations[i]; StringBuilder combination = new StringBuilder(sequenceToUpdate.Combinations[i]); //check if the combinations differ, and only process if they do if (!combination.Equals(combinationReference)) { for (int j = 0; j < sequenceToUpdate.Combinations[i].Length; j++) { if (combination[j].Equals('X') && !combinationReference[j].Equals('X')) { combination[j] = combinationReference[j]; var leftToProcess = combination.ToString().Substring(j); var leftToProcessReference = combinationReference.Substring(j); //minor benefit, check if any changes left in string so we avoid needlessly iterating over unchanged genes if (j + 1 != sequenceToUpdate.Combinations[i].Length && leftToProcess.Equals(leftToProcessReference)) { break; } } } } sequenceToUpdate.Combinations[i] = combination.ToString(); } }
static void Main() { try { StringBuilder str = new StringBuilder("Площадь"); PrintString(str); str.Append(" треугольника равна"); PrintString(str); str.AppendFormat(" {0:f2} см ", 123.456); PrintString(str); str.Insert(8, "данного "); PrintString(str); str.Remove(7, 21); PrintString(str); str.Replace("а", "о"); PrintString(str); Console.WriteLine("Введите первую строку для сравнения:"); StringBuilder str1 = new StringBuilder(Console.ReadLine()); Console.WriteLine("Введите вторую строку для сравнения:"); StringBuilder str2 = new StringBuilder(Console.ReadLine()); Console.WriteLine("Строки равны: " + str1.Equals(str2)); } catch { Console.WriteLine("Возникло исключение"); } }
public static void CheckMethod() { StringBuilder str1, str2; string no_permutation = "\nСтрока2 не является перестановкой букв Строки1"; string permutation = "\nСтрока2 является перестановкой букв Строки 1"; do { Console.Clear(); Console.Write("Введите 1 строку: "); str1 = new StringBuilder(Console.ReadLine()); Console.Write("\nВведите 2 строку: "); str2 = new StringBuilder(Console.ReadLine()); if (str1.Length != str2.Length) { Console.WriteLine(no_permutation); continue; } Sort(ref str1); Sort(ref str2); Console.WriteLine(str1); Console.WriteLine(str2); Console.WriteLine(str1.Equals(str2) ? permutation : no_permutation); } while (Console.ReadKey(true).Key != ConsoleKey.Escape); }
//підрахунок к-ті станів у які необхідно перейти, щоб прийти до розв'язку public int CountStatesToResult(int count) { StringBuilder allChilds = new StringBuilder(""); for (int i = 0; i < this.Array.Length; i++) { allChilds.Append(this.Array[i] + " "); } allChilds.Append(": "); foreach (State child in childs) { for (int i = 0; i < child.Array.Length; i++) { allChilds.Append(child.Array[i] + " "); } if (!allChilds.Equals("0 0 0 -1 1 1 1 1 ")) { count += 1; } allChilds.Append("\n"); } return(count); }
/// <summary> /// Full path to Artist folder /// </summary> /// <param name="artistSortName">Sort name of Artist to use for folder name</param> public static string ArtistPath(IRoadieSettings configuration, int artistId, string artistSortName, bool createIfNotFound = false) { SimpleContract.Requires <ArgumentException>(!string.IsNullOrEmpty(artistSortName), "Invalid Artist Sort Name"); SimpleContract.Requires <ArgumentException>(configuration.LibraryFolder.Length < MaximumLibraryFolderNameLength, $"Library Folder maximum length is [{ MaximumLibraryFolderNameLength }]"); var asn = new StringBuilder(artistSortName); foreach (var stringReplacement in FolderSpaceReplacements) { if (!asn.Equals(stringReplacement)) { asn.Replace(stringReplacement, " "); } } var artistFolder = asn.ToString().ToAlphanumericName(false, false).ToFolderNameFriendly().ToTitleCase(false); if (string.IsNullOrEmpty(artistFolder)) { throw new Exception($"ArtistFolder [{ artistFolder }] is invalid. ArtistId [{ artistId }], ArtistSortName [{ artistSortName }]."); } var afUpper = artistFolder.ToUpper(); var fnSubPart1 = afUpper.ToUpper().ToCharArray().Take(1).First(); if (!char.IsLetterOrDigit(fnSubPart1)) { fnSubPart1 = '#'; } else if (char.IsNumber(fnSubPart1)) { fnSubPart1 = '0'; } var fnSubPart2 = afUpper.Length > 2 ? afUpper.Substring(0, 2) : afUpper; if (fnSubPart2.EndsWith(" ")) { var pos = 1; while (fnSubPart2.EndsWith(" ")) { pos++; fnSubPart2 = fnSubPart2.Substring(0, 1) + afUpper.Substring(pos, 1); } } var fnSubPart = Path.Combine(fnSubPart1.ToString(), fnSubPart2); var fnIdPart = $" [{ artistId }]"; var maxFnLength = (MaximumArtistFolderNameLength - (fnSubPart.Length + fnIdPart.Length)) - 2; if (artistFolder.Length > maxFnLength) { artistFolder = artistFolder.Substring(0, maxFnLength); } artistFolder = Path.Combine(fnSubPart, $"{ artistFolder }{ fnIdPart }"); var directoryInfo = new DirectoryInfo(Path.Combine(configuration.LibraryFolder, artistFolder)); if (createIfNotFound && !directoryInfo.Exists) { directoryInfo.Create(); } return(directoryInfo.FullName); }
public static void CopyCSS() { Thread thread = new Thread(() => { StringBuilder CssBuilder = new StringBuilder(""); string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\Style.css"; bool dontRewrite = false; try { using (FileStream fs = new FileStream(@"ConfigurationFiles\Style.css", FileMode.Open)) { using (StreamReader sr = new StreamReader(fs, Encoding.UTF8)) { CssBuilder.Append(sr.ReadToEnd()); } } try { using (FileStream fs = new FileStream(path, FileMode.Open)) { using (StreamReader sr = new StreamReader(fs, Encoding.UTF8)) { StringBuilder comparer = new StringBuilder(""); comparer.Append(sr.ReadToEnd()); if (comparer.Equals(CssBuilder)) { dontRewrite = true; } } } } catch { if (!dontRewrite) { using (FileStream fs = new FileStream(path, FileMode.Create)) { using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8)) { sw.WriteLine(CssBuilder); } } } } } catch (FileNotFoundException) { MessageBox.Show("CSS configuration file is missing!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } catch (Exception) { MessageBox.Show("CSS file could not be copied!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }); thread.Start(); }
static void Main(string[] args) { var builder1 = new StringBuilder("あいう"); var builder2 = new StringBuilder("あいう"); Console.WriteLine(builder1 == builder2); Console.WriteLine(builder1.Equals(builder2)); }
public void Difference() { StringBuilder sOne = new StringBuilder("India"); StringBuilder sTwo = new StringBuilder("India"); Console.WriteLine(sOne == sTwo); // Comparing the reference. Console.WriteLine(sOne.Equals(sTwo)); // Comparing the content. }
public static void test_func() { StringBuilder sb1 = new StringBuilder("2a"); StringBuilder sb2 = new StringBuilder("2a"); Console.WriteLine(sb1 == sb2); Console.WriteLine(sb1.Equals(sb2)); }
private static void ProcessMessage(IntPtr param) { var message = Marshal.PtrToStructure <Msg>(param); if (message.Message != 0x0018) { return; } var box = message.Hwnd; var parent = GetParent(box); if (parent == IntPtr.Zero) { return; } var className = new StringBuilder(7); GetClassName(box, className, className.Capacity); if (!className.Equals("#32770")) { return; } if (!GetWindowRect(box, out var boxRect)) { return; } if (!GetWindowRect(parent, out var parentRect)) { return; } var width = boxRect.Right - boxRect.Left; var height = boxRect.Bottom - boxRect.Top; var left = (parentRect.Left + parentRect.Right) / 2 - width / 2; var top = (parentRect.Top + parentRect.Bottom) / 2 - height / 2; var screen = MonitorFromWindow(parent, MonitorDefaultTo.Nearest); var monitorInfo = MonitorInfo.Empty; if (GetMonitorInfo(screen, ref monitorInfo)) { left = Math.Max(monitorInfo.WorkArea.Left, Math.Min(monitorInfo.WorkArea.Right - width, left)); top = Math.Max(monitorInfo.WorkArea.Top, Math.Min(monitorInfo.WorkArea.Bottom - height, top)); } const SetWindowPosFlags commonFlags = SetWindowPosFlags.SynchronousWindowPosition | SetWindowPosFlags.IgnoreResize | SetWindowPosFlags.DoNotActivate | SetWindowPosFlags.DoNotChangeOwnerZOrder | SetWindowPosFlags.IgnoreZOrder; SetWindowPos(box, IntPtr.Zero, left, top, width, height, commonFlags); }
public IList <string> FindRepeatedDnaSequences2(string s) { var set = new HashSet <string>(); var resultSet = new HashSet <string>(); var sb = new StringBuilder(); var secondSb = new StringBuilder(); for (int i = 0; i < s.Length - 10; i++) { if (sb.Length > 0) { sb.Remove(0, 1); } while (sb.Length < 10) { char ch = s[i + sb.Length]; sb.Append(ch); } string substr = sb.ToString(); if (set.Contains(substr)) { continue; } secondSb.Clear(); for (int j = i + 1; j < s.Length - 10 + 1; j++) { if (secondSb.Length > 0) { secondSb.Remove(0, 1); } while (secondSb.Length < 10) { char ch = s[j + secondSb.Length]; secondSb.Append(ch); } if (sb.Equals(secondSb)) { set.Add(substr); break; } } } var result = new List <string>(); foreach (string item in set) { result.Add(item); } return(result); }
public Task ParseEnvironmentVariable_failure() { StringBuilder builder = new StringBuilder(); builder.Equals(new StringBuilder()); var exception = Assert.Throws <Exception>(() => ClipboardEnabled.ParseEnvironmentVariable("foo")); return(Verify(exception)); }
public void PositiveCaseTest() { // Act StringTokenziLogic stringTokenziLogic = new StringTokenziLogic(); StringBuilder actual = stringTokenziLogic.TestCaseStrTokenzi(inputString); // Assert Assert.IsTrue(expected.Equals(actual)); }
public IntPtr FindTaskBar(string title) { IntPtr ret = IntPtr.Zero; WindowsAPI.EnumWindows(new EnumWindProc((hwnd, lptr) => { try { StringBuilder szClass = new StringBuilder(); if (!WindowsAPI.GetWindow(hwnd, WindowsAPI.GW_OWNER) /*&& WindowAPI.IsWindowVisible(hwnd)*/) // 滤掉不在任务栏显示的窗口 { WindowsAPI.GetClassName(hwnd, szClass, 256); if (!szClass.Equals("Shell_TrayWnd") &&// 滤掉任务栏本身 !szClass.Equals("Progman") // 滤掉桌面 ) { if (WindowsAPI.GetWindowLong(hwnd, WindowsAPI.GWL_EXSTYLE & WindowsAPI.WS_EX_TOOLWINDOW)) { return(true); } //这就是你想要的窗口了。 StringBuilder szTitle = new StringBuilder(); WindowsAPI.GetWindowText(hwnd, szTitle, 256); if (szTitle.Equals(title)) { ret = hwnd; return(false); } } } return(true); } catch (Exception e) { } return(true); }), IntPtr.Zero); return(ret); }
public virtual bool runTest() { Console.Error.WriteLine( "Co1454ctor_Strings. runTest started." ); int iCountErrors = 0; StringBuilder sbl2 = null; String str2b = null; String str2c = null; String str2d = null; String str2e = null; String str2_All = null; String str2_Some = null; String str9 = null; IntlStrings intl = new IntlStrings(); str9 = intl.GetString(6, true, true); str2_All = str9; if ( ! str9.Equals( str2_All ) ) { iCountErrors += 1; Console.Error.WriteLine( "POINTTOBREAK: Error E_6555im! (Co1454ctor_Strings)" ); } str2b = "Bb"; str2c = "Cc"; str2d = "Dd"; str2e = "Ee"; str2_All = "BbCcDdEe"; str9 = "BbCcDdEe" ; if ( ! str9.Equals( str2_All ) ) { iCountErrors += 1; Console.Error.WriteLine( "POINTTOBREAK: Error E_638im! (Co1454ctor_Strings)" ); } sbl2 = new StringBuilder( "BbCcDd" ); sbl2.Append( str2e ); str9 = sbl2.ToString(); if ( ! str9.Equals( str2_All ) ) { iCountErrors += 1; Console.Error.WriteLine( "POINTTOBREAK: Error E_517cw! (Co1454ctor_Strings)" ); } str9 = "Bb" + "Cc" +"Dd" ; str2_Some = "BbCcDd"; if ( ! str9.Equals( str2_Some ) ) { iCountErrors += 1; Console.Error.WriteLine( "POINTTOBREAK: Error E_460is! (Co1454ctor_Strings)" ); } str9 = str2b + str2c + str2d ; str9 = new StringBuilder( str9 ).Append( str2e ).ToString(); if ( ! str9.Equals( str2_All ) ) { iCountErrors += 1; Console.Error.WriteLine( "POINTTOBREAK: Error E_253xi! (Co1454ctor_Strings)" ); } if ( iCountErrors == 0 ) { return true; } else { return false;} }
public override bool Equals(object obj) { if (obj is Class other) { return(Methods.Equals(other.Methods) && Type.GenericArguments.Count == other.Type.GenericArguments.Count); } return(false); }
public void IntroduceMe() { // Intended output, but pieces can be left out: // Hi, I am {FirstName} {LastName}. // I am {Age} years old and my eye color is {EyeColor} StringBuilder Line1 = new StringBuilder(); StringBuilder Line2 = new StringBuilder(); Line1.Append("Hello"); if (!FirstName.Equals("") || !LastName.Equals("")) { Line1.Append(", I am "); if (!FirstName.Equals("")) { Line1.Append(FirstName); } if (!FirstName.Equals("") && !LastName.Equals("")) { Line1.Append(" "); } if (!LastName.Equals("")) { Line1.Append(LastName); } Line1.Append("."); } else { Line1.Append("."); } if (!EyeColor.Equals("") && Age != 0) { Line2.Append($"I am {Age} years old and my eye color is {EyeColor}."); } else if (!EyeColor.Equals("")) { Line2.Append($"My eye color is {EyeColor}."); } else if (Age != 0) { Line2.Append($"I am {Age} years old."); } if (!Line1.Equals("")) { Console.WriteLine(Line1); } if (!Line2.Equals("")) { Console.WriteLine(Line2); } return; }
public static void Main() { int count = int.Parse(Console.ReadLine()); int[] numbers = Console.ReadLine().Trim().Split().Select(int.Parse).ToArray(); bool haveMatch = false; StringBuilder left = new StringBuilder(); StringBuilder right = new StringBuilder(); for (int a = 0; a < count; a++) { for (int b = 0; b < count; b++) { for (int c = 0; c < count; c++) { for (int d = 0; d < count; d++) { if (a != b && a != c && a != d && b != c && b != d && c != d) { left.Append(numbers[a]); left.Append(numbers[b]); right.Append(numbers[c]); right.Append(numbers[d]); if (left.Equals(right)) { haveMatch = true; Console.WriteLine("{0}|{1}=={2}|{3}", numbers[a], numbers[b], numbers[c], numbers[d]); } left.Clear(); right.Clear(); } } } } } if (!haveMatch) { Console.WriteLine("No"); } }
static StringBuilder Evaluate(StringBuilder buffer, string tag = "") { // the method walks through "buffer" character by character // and prints any of them to the output in accordance to the type of surrounding pair of tags // if a pair of tags are found inside the buffer // the method calls itself with the text inside those tags (using recursion) // then the result is "replaced" within the buffer. StringBuilder result = new StringBuilder(); if (tag == "del") return result; // if surroundng tag is del - returns empty result bool isTag = false; // indicates if we are reading the tag name bool inTag = false; // indicates if we are reading the text between pair of tags StringBuilder anyTag = new StringBuilder(); // holds the tag name of any found tag in the text StringBuilder openTag = new StringBuilder(); // holds the tag name of the relevant opening tag StringBuilder toEvaluate = new StringBuilder(); // holds the text between a pair of tags int nestedEqualTags = 0; // counts how many equal opening tags are found (the same number of closing tags we must have to make a pair) for (int i = 0; i < buffer.Length; i++) { char symbol = buffer[i]; if (!isTag && symbol == '<') // tag start { isTag = true; continue; } if (isTag && symbol == '>') // tag end { isTag = false; if (openTag.Length == 0) // we don't have any opening tags up to the moment { openTag.Append(anyTag); inTag = true; anyTag.Clear(); } else { if (openTag.Equals(anyTag)) nestedEqualTags++; // a new equal opening tag has been found - counts it if (anyTag[0] == '/' && openTag.ToString() == anyTag.ToString(1, anyTag.Length - 1) && nestedEqualTags == 0) // the closing tag that makes pair with the opening tag has been found { inTag = false; // we already have a pair of tags inside the buffer - evaluates it toEvaluate = Evaluate(toEvaluate, openTag.ToString()); // and then saves the result into buffer but after current position if (i == buffer.Length - 1) // if end of buffer has been found { buffer.Append(toEvaluate); // appends it to the end of buffer } else { buffer.Insert(i+1, toEvaluate); // otherwise iserts it } anyTag.Clear(); openTag.Clear(); toEvaluate.Clear(); // clears all tag holders } else // we don't have a pair of tags or the pair is not the most outer one { // if we have more than one equal opening tags - counts the inner pair of them if (anyTag[0] == '/' && openTag.ToString() == anyTag.ToString(1, anyTag.Length - 1)) nestedEqualTags--; // since this is not the most outer tag puts it to the evaluation buffer toEvaluate.Append("<" + anyTag + ">"); anyTag.Clear(); // clears the tag appended already } } continue; // goes to the next buffer position } if (!isTag && !inTag) // standard output { switch (tag) // do the job of the corresponding tag { case "upper": result.Append(char.ToUpper(symbol)); break; case "lower": result.Append(char.ToLower(symbol)); break; case "toggle": if (Char.IsUpper(symbol)) result.Append(char.ToLower(symbol)); // toggles the case of the character else result.Append(char.ToUpper(symbol)); break; case "rev": result.Insert(0, symbol); // text reversing is implemented through insert at the current buffer begining break; default: result.Append(symbol); // normal text is just appended to the end of the current buffer break; } } else if (isTag) //we are reading tag name { anyTag.Append(symbol); } else // we are in nested tag - just append to the evaluation buffer for further processing { toEvaluate.Append(symbol); } } return result; }
public static int Main(string[] args) { string strManaged = "Managed"; string strRet = "a"; StringBuilder strBRet = new StringBuilder("a", 1); string strNative = " Native"; StringBuilder strBNative = new StringBuilder(" Native", 7); Console.WriteLine("[Calling PInvokeDef.Marshal_InOut]"); //since the out attributes doesnt work for string, so i dont check the out value. string strPara2 = new string(strManaged.ToCharArray()); string strRet2 = PInvokeDef.Marshal_InOut(strPara2); if (!strRet2.Equals(strRet)) { ReportFailure("Method PInvokeDef.Marshal_InOut[Managed Side],The Return string is wrong", strRet, strRet2); } //TestMethod3 Console.WriteLine("[Calling PInvokeDef.Marshal_Out]"); string strPara3 = strManaged; string strRet3 = PInvokeDef.Marshal_Out(strPara3); if (!strRet.Equals(strRet3)) { ReportFailure("Method PInvokeDef.Marshal_Out[Managed Side],The Return string is wrong", strRet, strRet3); } if (!strManaged.Equals(strPara3)) { ReportFailure("Method PInvokeDef.Marshal_Out[Managed Side],The Parameter string is Changed", strManaged, strPara3); } //TestMethod5 Console.WriteLine("[Calling PInvokeDef.MarshalPointer_InOut]"); string strPara5 = strManaged; string strRet5 = PInvokeDef.MarshalPointer_InOut(ref strPara5); if (!strRet5.Equals(strRet)) { ReportFailure("Method PInvokeDef.MarshalPointer_InOut[Managed Side],The Return string is wrong", strRet, strRet5); } if (!strPara5.Equals(strNative)) { ReportFailure("Method PInvokeDef.MarshalPointer_InOut[Managed Side],The Passed string is wrong", strNative, strPara5); } //TestMethod6 Console.WriteLine("[Calling PInvokeDef.MarshalPointer_Out]"); string strPara6;// = String.Copy(strManaged); string strRet6 = PInvokeDef.MarshalPointer_Out(out strPara6); if (!strRet6.Equals(strRet)) { ReportFailure("Method PInvokeDef.MarshalPointer_Out[Managed Side],The Return string is wrong", strRet, strRet6); } if (!strPara6.Equals(strNative)) { ReportFailure("Method PInvokeDef.MarshalPointer_Out[Managed Side],The Passed string is wrong", strNative, strPara6); } //TestMethod7 Console.WriteLine("[Calling PInvokeDef.MarshalStrB_InOut]"); StringBuilder strPara7 = new StringBuilder(strManaged); StringBuilder strRet7 = PInvokeDef.MarshalStrB_InOut(strPara7); if (!IsEqual(strRet7,strBRet)) { ReportFailure("Method PInvokeDef.MarshalStrB_InOut[Managed Side],The Return string is wrong", strRet, strRet7.ToString()); } if (!strPara7.Equals(new StringBuilder(strNative))) { ReportFailure("Method PInvokeDef.MarshalStrB_InOut[Managed Side],The Passed string is wrong", strNative, strPara7.ToString()); } //TestMethod8 Console.WriteLine("[Calling PInvokeDef.MarshalStrB_Out]"); StringBuilder strPara8;// = new StringBuilder(strManaged); StringBuilder strRet8 = PInvokeDef.MarshalStrB_Out(out strPara8); if (!IsEqual(strRet8, strBRet)) { ReportFailure("Method PInvokeDef.MarshalStrB_Out[Managed Side],The Return string is wrong", strRet, strRet8.ToString()); } if (!IsEqual(strPara8,strBNative)) { ReportFailure("Method PInvokeDef.MarshalStrB_Out[Managed Side],The Passed string is wrong", strNative, strPara8.ToString()); } //TestMethod9 Console.WriteLine("[Calling PInvokeDef.MarshalStrWB_InOut]"); StringBuilder strPara9 = new StringBuilder(strManaged, strManaged.Length); StringBuilder strRet9 = PInvokeDef.MarshalStrWB_InOut(strPara9); if (!IsEqual(strRet9, strBRet)) { ReportFailure("Method PInvokeDef.MarshalStrWB_InOut[Managed Side],The Return string is wrong", strRet, strRet9.ToString()); } if (!IsEqual(strPara9,strBNative)) { ReportFailure("Method PInvokeDef.MarshalStrWB_InOut[Managed Side],The Passed string is wrong", strNative, strPara9.ToString()); } #region DelegatePinvoke //TestMethod11 Del_MarshalPointer_InOut d1 = new Del_MarshalPointer_InOut(PInvokeDef.MarshalPointer_InOut); string strPara11 = new string(strManaged.ToCharArray()); string strRet11 = d1(ref strPara11); if (!strRet11.Equals(strRet)) { ReportFailure("Method Del_MarshalPointer_InOut[Managed Side],The Return string is wrong", strRet, strRet11); } if (!strPara11.Equals(strNative)) { ReportFailure("Method Del_MarshalPointer_InOut[Managed Side],The Passed string is wrong", strNative, strPara11); } Del_Marshal_Out d2 = new Del_Marshal_Out(PInvokeDef.Marshal_Out); string strPara12 = strManaged; string strRet12 = d2(strPara12); if (!strRet.Equals(strRet12)) { ReportFailure("Method Del_Marshal_Out[Managed Side],The Return string is wrong", strRet, strRet12); } if (!strManaged.Equals(strPara12)) { ReportFailure("Method Del_Marshal_Out[Managed Side],The Parameter string is Changed", strManaged, strPara12); } #endregion #region ReversePInvoke Del_MarshalStrB_InOut d3 = new Del_MarshalStrB_InOut(Call_Del_MarshalStrB_InOut); if (!PInvokeDef.ReverseP_MarshalStrB_InOut(d3, "ă")) { ReportFailure("Method ReverseP_MarshalStrB_InOut[Managed Side],return value is false"); } Del_MarshalStrB_Out d4 = new Del_MarshalStrB_Out(Call_Del_MarshalStrB_Out); if (!PInvokeDef.ReverseP_MarshalStrB_Out(d4)) { ReportFailure("Method ReverseP_MarshalStrB_Out[Managed Side],return value is false"); } #endregion return ExitTest(); }
public static void TestEquals(StringBuilder sb1, StringBuilder sb2, bool expected) { Assert.Equal(expected, sb1.Equals(sb2)); }