Geekpedia Tutorials Home

Building a C# Chat Client and Server

Building a C# Chat Client and ServerA step by step tutorial teaching you how to create your own chat client and chat server easily in C#, for local networks or the Internet.

in C# Programming Tutorials

Getting Hard Drive Information

Getting Hard Drive InformationA C# tutorial showing you how to make use of WMI to extract information on disk drives, such as model, capacity, sectors and serial number.

in C# Programming Tutorials

UPS Shipping Calculator

UPS Shipping CalculatorThis tutorial will teach you how to calculate the shipping cost based on the weight, height, length and depth of the box, the distance and the UPS service type.

in PHP Programming Tutorials

Create Your Own Rich Text Editor

Create Your Own Rich Text EditorCreating a Rich Text Editor using JavaScript is easier to do than you might think, thanks to the support of modern browsers; this tutorial will walk you through it.

in JavaScript Programming Tutorials
Search
Tutorials
Programming Tutorials
IT Jobs
From CareerBuilder

All about strings

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

On Saturday, May 15th 2004 at 03:29 PM
By Andrew Pociu (View Profile)
****-   (Rated 3.9 with 16 votes)
Contextual Ads
More C# Resources
Advertisement

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
Digg Digg It!     Del.icio.us Del.icio.us     Reddit Reddit     StumbleUpon StumbleIt     Newsvine Newsvine     Furl Furl     BlinkList BlinkList

Rate Rate this tutorial
Comment Current Comments
by Hennie on Thursday, February 17th 2005 at 08:04 AM

Excellent tutorial. Great examples. Thank you.

by suman on Tuesday, March 8th 2005 at 02:55 AM

hello sir
i just want to say that
change event of text box the select item of list box will change

by arzu on Monday, August 15th 2005 at 10:17 AM

hi sir,I want to print double forward slash as a path for a server like https://.....how can I save // to seem l&#305;ke comment???

by steve on Tuesday, August 16th 2005 at 03:18 PM

how can you forget how to search a string!?!??!?!

by Sreenath on Thursday, August 18th 2005 at 02:27 PM

OK, REVERSING A STRING IS FOR PRIMITIVE PEOPLE. I have one question how you reverse whole document. Oops don't tell convert document into a string and then reverse. It eats up lot of memory!!!
I am looking this functionality with a minimal code..

Using a pointers ? guys any idea ?

by Andrei Pociu on Thursday, August 18th 2005 at 02:56 PM

What kind of document? Word? Or simply a text file?

by Webstorm on Monday, September 12th 2005 at 10:05 AM

"I have one question how you reverse whole document."

I already done this with Wave file to hear the reverse (preserving headers).

You need to create a new file, open your source file with random access, read your source file block by block, starting from the end (using seek), reversing each block, and writing it to your new file.

by nafissur on Thursday, October 27th 2005 at 07:41 AM

hi the article was excellent and i exactly got the thing that i was searching for the past 4hrs.

by kriss on Monday, March 6th 2006 at 10:04 AM

very very nice article on strings boss,really its very very good,keep it up

by Usman on Monday, March 13th 2006 at 01:07 AM

can any1 tel me what can be the maximum length of a string in c#.net ?

by Andrei Pociu on Monday, March 13th 2006 at 12:25 PM

There is no limit set for the string datatype. As long as you store a decent amount of characters in that string (less than 10,000), you shouldn't worry about slowing down the application, either.

For more information on C# data types, see <a href="http://www.geekpedia.com/tutorial29_Csharp-data-types.html">the C# data types tutorial</a>.

by GeekPediaFan on Wednesday, April 18th 2007 at 09:08 AM

// You can have some fun with version 3.0,
// add the following class and you automatically
// get a .Reverse() method on all your strings.
public static class StringExtensions
{
public static string Reverse( this string input )
{
string result = null;

if ( input != null )
{
var output = new char[input.Length];
var index = output.Length;
foreach ( char character in input )
{
output[--index] = character;
}
result = new String( output );
}

return result;
}
}

by NMY on Thursday, October 18th 2007 at 01:32 PM

Crap... I\'m looking for any char (?,x) or any string (*) and can\'t find a shit...

by shwetha on Wednesday, August 4th 2010 at 10:20 PM

i would like to know how to find the length of the string without using the length function..

by shwetha on Wednesday, August 4th 2010 at 10:20 PM

i would like to know how to find the length of the string without using the length function..


Comment Comment on this tutorial
Name: Email:
Message:
Comment Related Tutorials
There are no related tutorials.

Comment Related Source Code
There is no related source code.

Jobs C# Job Search
My skills include:
Enter a City:

Select a State:


Advanced Search >>
Sponsors
Discover Geekpedia

Other Resources