All about strings

How to compare two strings, reverse a string, search in a string and many other techniques, each with examples.

Finding the length of a string

The easy way to find the length of a string in C# is using the ‘Length’ property. Length of the string includes spaces and all the special characteres.


using System;
class Class1
{
    [STAThread]
    static void Main(string[] args)
    {
        string someText = "Count this!";
        int someTextLength = someText.Length;
        Console.WriteLine("The string '{0}' has a length of {1} characters", someText, someTextLength);
    }
}

Reversing a string

We reverse a string by taking each character in that string and reversing its position. We do this with the help of the string index that is similar to an array.


using System;
class Class1
{
    [STAThread]
    static void Main(string[] args)
    {
        // The original string we want to be reversed
        string someText = "Reverse this!";

        // If we don't set it to "" we get a compile error
        // because the variable needs to be assigned with
        // something before using 'reversed += ...'
        string reversed = "";

        // While we have characters in the string continue to reverse
        for(int i = someText.Length - 1; i >= 0; i--)
        {

            // someText[i] is the string index,
            // acts very similar to an array
            reversed += someText[i];
        }

        // Display the final result
        Console.WriteLine("Original: {0}\nReversed: {1}", someText, reversed);
    }
}

Comparing strings

There are several ways to compare a string. Although for sorting strings using method CompareTo() is probably the best way, because it returns 0 if the values are equal, -1 if the first value (that invokes) is smaller than the second value and 1 if the first value is bigger than the second value.


using System;

class Class1
{
    [STAThread]
    static void Main(string[] args)
    {
        string str1 = "";
        string str2 = "";
        Console.WriteLine("Please enter the first string:");
        str1 = Console.ReadLine();
        Console.WriteLine("Please enter the second string:");
        str2 = Console.ReadLine();
        if(str1.CompareTo(str2) == 0)
        {
            Console.WriteLine("{0} = {1}", str1, str2);
        }
        else if(str1.CompareTo(str2) == -1)
        {
            Console.WriteLine("{0} < {1}", str1, str2);
        }
        else if(str1.CompareTo(str2) == 1)
        {
            Console.WriteLine("{0} > {1}", str1, str2);
        }
    }
}



Remember: This is case sensitive.

IndexOf and LastIndexOf

The position of a character / string in a string

Method IndexOf returns the index of a searched character in a string.
For example if we searched for character ‘e’ in the string ‘This is the string in which we search.’ IndexOf would return 10.
You may say… hmm… ‘e’ is character number 11 in the string, not 10. I would reply – you are still not used to counting from 0?

Let’s see the code now.


using System;

class Class1
{
    [STAThread]
    static void Main(string[] args)
    {
        // The string in which we search
        string str1 = "This is the string in which we search.";

        // The final string, with the search term highlighted
        string str2 = "";
        
        // The character or string we search for
        string searchTerm;

        // The original str1
        Console.WriteLine("SEARCH IN: {0}", str1);

        // Request a search string or character from the user
        Console.Write("FOR: ");
        searchTerm = Console.ReadLine();

        // Display the index (position) of the searched term in the str1
        // If the character wasn't found returns -1
        Console.WriteLine("INDEX: {0}", str1.IndexOf(searchTerm));

        // Loop through str1
        for(int i = 0; i < str1.Length; i++)
        {
            // If the current index (position) in the string is the same
            // as the index where the term was found we shall highlight it
            if(i == str1.IndexOf(searchTerm))
            {
                // Build a new string, str2 with the highlighted character
                // Add the character that was found, between < and >
                str2 += "<" + str1[i] + ">";
            }
            else
            {
                // If not just add the letter to the new string - str2
                str2 += str1[i];
            }
        }
        // Write the final result - str2
        Console.WriteLine("RESULT: {0}", str2);
    }
}



Compile with Ctrl + F5 in Visual C# .NET and test it.

You can see that if you search for ‘is’, for example, the result is:


Th<i>s is the string in which we search.



It only highlights the first character, although the search is actually for ‘is’ and the result is correct.
You can test this by searching ‘str’ that returns:


This is the <s>tring in which we search.



Remember that the search is case-sensitive. If you search for ‘th’ you won’t get ‘his is…’, you will get:


This is <t>he string in which we search.



If the character or string is not found IndexOf returns -1.

You can do more with IndexOf, like searching from a specified index or searching only a specified amount of characters.
For more information about IndexOf view the MSDN Library.

LastIndexOf performs similar, only that it checks for the occurence of the searched term from the end to the beginning.

String StartsWith and EndsWith

Create a new Windows Application project ‘stringStart’.
Add to it a TextBox ‘txtBegin’ and a ListBox ‘listWords’.
The following is the complete code that should make the program work. The comments make the code self-explanatory.


using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace stringStart
{
    /// <summary>
    /// Summary description for Form1.
    /// </summary>
    public class Form1 : System.Windows.Forms.Form
    {
        private System.Windows.Forms.ListBox listWords;
        private System.Windows.Forms.TextBox txtBegin;
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.Container components = null;

        public Form1()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            //
            // TODO: Add any constructor code after InitializeComponent call
            //
        }

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose( bool disposing )
        {
            if( disposing )
            {
                if (components != null) 
                {
                    components.Dispose();
                }
            }
            base.Dispose( disposing );
        }

        #region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.listWords = new System.Windows.Forms.ListBox();
            this.txtBegin = new System.Windows.Forms.TextBox();
            this.SuspendLayout();
            // 
            // listWords
            // 
            this.listWords.Location = new System.Drawing.Point(8, 40);
            this.listWords.Name = "listWords";
            this.listWords.Size = new System.Drawing.Size(272, 225);
            this.listWords.TabIndex = 0;
            // 
            // txtBegin
            // 
            this.txtBegin.Location = new System.Drawing.Point(8, 8);
            this.txtBegin.Name = "txtBegin";
            this.txtBegin.Size = new System.Drawing.Size(272, 20);
            this.txtBegin.TabIndex = 1;
            this.txtBegin.Text = "";
            this.txtBegin.TextChanged += new System.EventHandler(this.txtBegin_TextChanged);
            // 
            // Form1
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(292, 273);
            this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                                          this.txtBegin,
                                                                          this.listWords});
            this.Name = "Form1";
            this.Text = "Form1";
            this.Load += new System.EventHandler(this.Form1_Load);
            this.ResumeLayout(false);

        }
        #endregion

        /// <summary>
        /// The main entry point for the application.
        /// </summary>

        // The array of words that we want to have in the ListBox
        string[] wordsArray = {"mask", "mason", "masque", "massacre", "massage", "master", "mastery"};

        [STAThread]
        static void Main() 
        {
            Application.Run(new Form1());
        }

        private void txtBegin_TextChanged(object sender, System.EventArgs e)
        {
            // Clear the list of any previous words
            listWords.Items.Clear();
            // Loop through the array of words
            foreach(string word in wordsArray)
            {
                // If the current word starts with the string in the TextBox...
                if(word.StartsWith(txtBegin.Text))
                {
                    //... add it to the ListBox
                    listWords.Items.Add(word);
                }
            }
        }

        private void Form1_Load(object sender, System.EventArgs e)
        {
            // Loop through the array to add items to the ListBox
            foreach(string word in wordsArray)
            {
                listWords.Items.Add(word);
            }
        }
    }
}



If you type ‘mas’ the word in the ListBox remain the same, because they all start with ‘mas’.
If you type ‘mass’ only the words that begin with ‘mass’ remain – ‘massacre’ and ‘massage’.

For finding the words that end with one or more specified characters just replace


if(word.StartsWith(txtBegin.Text))



with


if(word.EndsWith(txtBegin.Text))



Compile and type ‘e’ in the TextBox. In the ListBox appear only the words that end with ‘e’ – ‘masque’, ‘massacre’ and ‘massage’.

Remember: This is case sensitive.

SubString

I brought you an example with self-explanatory code, again 


using System;
class Class1
{
    [STAThread]
    static void Main(string[] args)
    {
        // The string on which we operate
        string str1 = "Take the substring out of me";

        // The starting and ending point
        int start, end;

        // Show the string
        Console.WriteLine(str1);

        // Request the start position from the user and hold it in variable 'start'
        Console.Write("Please enter the starting position: ");
        start = Convert.ToInt32(Console.ReadLine());

        // Request the end position from the user and hold it in variable 'end'
        Console.Write("Please enter the ending position: ");
        end = Convert.ToInt32(Console.ReadLine());

        // Display the characters between the starting and the ending position
        Console.WriteLine(str1.Substring(start, end));
    }
}



Now test it. For the starting position enter 5 and for the ending position enter 20. You will get ‘the substring out of’.

Do not try to enter a value bigger than the length of the string for the starting or ending point or you’ll get an ugly error.

ToUpper() and ToLower()

Converts a string all to uppercase or lowercase. So simple to use that I didn’t want to mention it in the first place.


using System;
class Class1
{
    [STAThread]
    static void Main(string[] args)
    {
        string str1;
        Console.WriteLine("Enter the string: ");
        str1 = Console.ReadLine();
        Console.WriteLine("lowercase: {0}", str1.ToLower());
        Console.WriteLine("UPPERCASE: {0}", str1.ToUpper());
    }
}

Trim

Trim cuts the empty space at the beginning and at the end of a string.
Using trim you can clean a string like ” I’m going to be trimmed “, the result beeing “I’m going to be trimmed”.


using System;
class Class1
{
    [STAThread]
    static void Main(string[] args)
    {
        string str1;
        Console.WriteLine("Enter the string: ");
        str1 = Console.ReadLine();
        Console.WriteLine("Trimmed: {0}", str1.Trim());
    }
}

Replace

You can easily replace each occurence of a character or string in a string using method Replace():


using System;
class Class1
{
    [STAThread]
    static void Main(string[] args)
    {
        string str1 = "Geekpedia.com";
        Console.WriteLine(str1);
        Console.WriteLine("After replacing 'e' with 'i':");
        Console.WriteLine(str1.Replace('e', 'i'));
    }
}



The result is of course:


Geekpedia.com
After replacing 'e' with 'i':
Giikpidia.com
Press any key to continue

Nathan Pakovskie is an esteemed senior developer and educator in the tech community, best known for his contributions to Geekpedia.com. With a passion for coding and a knack for simplifying complex tech concepts, Nathan has authored several popular tutorials on C# programming, ranging from basic operations to advanced coding techniques. His articles, often characterized by clarity and precision, serve as invaluable resources for both novice and experienced programmers. Beyond his technical expertise, Nathan is an advocate for continuous learning and enjoys exploring emerging technologies in AI and software development. When he’s not coding or writing, Nathan engages in mentoring upcoming developers, emphasizing the importance of both technical skills and creative problem-solving in the ever-evolving world of technology. Specialties: C# Programming, Technical Writing, Software Development, AI Technologies, Educational Outreach

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top