Compare the content of two StringBuilders



Equals method is used in C# to compare the content of two StringBuilders.

The following are our two StringBuilders −

// first
StringBuilder str1 = new StringBuilder();
str1.Append("Tim");
str1.Append("Tom");
str1.Append("Henry");

// second
StringBuilder str2 = new StringBuilder();
str2.Append("John");
str2.Append("David");
str2.Append("Beth");

Now use the Equals() method to compare both the methods −

if (str1.Equals(str2)) {
   Console.WriteLine("Contents are equal!");
}

The following is the complete code −

Example

 Live Demo

using System;
using System.Text;

class Demo {
   static void Main() {
      // first
      StringBuilder str1 = new StringBuilder();
      str1.Append("Tim");
      str1.Append("Tom");
      str1.Append("Henry");

      // second
      StringBuilder str2 = new StringBuilder();
      str2.Append("John");
      str2.Append("David");
      str2.Append("Beth");

      // check for equality
      if (str1.Equals(str2)) {
         Console.WriteLine("Contents are equal!");
      } else {
         Console.WriteLine("Contents are unequal!");
      }
   }
}

Output

Contents are unequal!
karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know


Advertisements