String Manipulation in C#

C# provides string type that contains a lot of methods to manipulate strings. For example, you can use C# string manipulation methods to find the length of a string, convert a string to an array of characters, change cases of a string to lower case or upper case, find the position of a substring in another string, get a substring from a string, compare two strings, remove spaces from a string, check a string whether it contains a substring at the beginning and the end of the string, split a string in to an array of string, insert a substring in another string, remove a substring from a string, and replace an existing substring with a new substring in a string. The C# string manipulation property, and  methods that can handle those such things can be Length property, ToCharArray(), ToLower(), ToUpper(), IndexOf(), LastIndexOf(), SubString(), CompareTo(), Trim(), TrimEnd(), TrimStart(), StartsWith(), EndsWith(), Split(), Insert(), Remove(), and Replace().

Length of a string

The length property can be used to count the number of characters in a string object. It is much like that you count the number of elements in an array object. In the example below we use the length property to check whether the user entered the correct length of password field that is greater than 8 characters.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
   strmanip();
   Console.ReadLine();
}

static void strmanip(){
  string name;
  string password;
  Console.Write("Enter Username:");
  name=Console.ReadLine();
  Console.Write("Enter Password:");
  password= Console.ReadLine();

  if (name!=""){
      if (password.Length > 8)
         Console.WriteLine("Welcome!");
     else Console.WriteLine("The password must be greater than 8 characters.");
  }

else Console.WriteLine("The Username can't be blank.");


        }
 }

ToCharArray() method

The ToChartArray() method can be used to convert a string to an array of characters. This enables you to access each character of the string individually.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
  strmanip();
  Console.ReadLine();
}

static void strmanip(){
  string st = "C# programming";
  char[] arrst = st.ToCharArray();
  foreach(char c in arrst)
  Console.WriteLine("{0}",c) ;



                }      
      }
}

IndexOf() and LastIndexOf() methods

You can use the IndexOf (char_value) to find the position of the first occurrence of a character in an invoking string. By using LastIndexOf (char_value) method you will get the position of the character that is found lastly in the invoking string. Each of the two method returns -1 if the target character is not found in the string.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
  strmanip();
  Console.ReadLine();
}

static void strmanip(){
     string st = "C# programming or Csharp programming";
     Console.WriteLine("The first occurrence of C character is: {0}",   st.IndexOf('C'));
     Console.WriteLine("The last occurrence of C charcter is: {0}", st.LastIndexOf('C'));




                }
      }
}

ToLower() and ToUpper() methods

The ToLower() and ToUpper() methods are used to change the cases of a string to lower case and to upper case respectively.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
  strmanip();
  Console.ReadLine();
}

static void strmanip(){
  string st = "C# programming";
  Console.WriteLine("{0}",st.ToLower() ) ;
  Console.WriteLine("{0}", st.ToUpper());



                }
     }
}

TrimStart(), TrimEnd(), and Trim() methods

You can remove unnecessary spaces from a string by using the Trim(), TrimStart(), and TrimEnd() methods. The Trim() method can remove spaces at the beginning and at the end of the string. If you want to remove spaces only at the beginning or at the end of the string, you can use TrimStart() or TrimEnd() method respectively.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
  strmanip();
  Console.ReadLine();
}

static void strmanip(){
  string st = " C# programming ";
  Console.WriteLine(st.Trim());
  Console.WriteLine(st.TrimStart());
  Console.WriteLine(st.TrimEnd());




                }

      }

}

Substring() method

The Substring(start_pos, [length]) method can be used to cut out a substring with the number of characters specified by length argument from a string by taking from the start_pos argument. The length argument is optional. If you do not specify this argument the substring will contain characters by starting from the character specified by the start argument to the last character of the string.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
  strmanip();
  Console.ReadLine();
}

static void strmanip(){
  string st = "C# programming or Csharp programming";
  string subst = st.Substring(0, 2);
  Console.WriteLine("{0}", subst);



                }

      }

}

For another example, we use the Substring() and IndexOf() methods to validate an e-mail address. The e-mail is valid if it contains the @ and . characters. The valid . character is the . character that stays after the @ character in he email string.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
strmanip();
test();
Console.ReadLine();
}

static void strmanip(){
string email="";
string subemail="";
Console.Write("Enter your e-mail address:");
email=Console.ReadLine();
int pos = email.IndexOf('@');
if(pos!=-1)
subemail = email.Substring(email.IndexOf('@'));
if (subemail.IndexOf('.')!=-1) Console.WriteLine("Valid e-maild address!");

else Console.WriteLine("Invalid e-mail address!");


    }
  }
}

CompareTo() method

You can use the CompareTo(string) method to compare the invoking string with the string specified by the string argument. This function returns 0 if both strings are equal. It returns 1 if the invoking string is greater than the string specified by the string argument, otherwise it returns -1.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
  strmanip();
  Console.ReadLine();
}

static void strmanip(){
  string st = "C# programming";
  if (st.CompareTo("Csharp programming") == 0)
  Console.WriteLine("Both strings are equal.");
  else Console.WriteLine("Both strings are not equal.");



                }

      }

}



StartsWith() and EndsWith() methods

You can use the StartsWith(substring) method to check whether a substring contains at the beginning of a string. If you want to check whether a substring contains at the end of the string you can use the EndsWith(substring) method. Both methods return boolean value(true or false).

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.IO;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
  strmanip();
  Console.ReadLine();
}

static void strmanip(){
   string stfilename = "";
   Console.Write("Enter the file name and its path:");
   stfilename = Console.ReadLine();
   if (stfilename.EndsWith(".txt"))
   {
      FileStream fs;
      StreamReader fr;
      fs = new FileStream(stfilename, FileMode.Open, FileAccess.Read);
      fr = new StreamReader(fs);
      string content = fr.ReadToEnd();
      Console.WriteLine(content);
      Console.ReadLine();

}
else Console.WriteLine("Invalid file type!");



                }

      }

}

Split() method to split string

The Split(char_separator) method can be used to split a string in to an array of substrings. The string is split according to the separator character. In the example below we use a space(' ') character as a separator to split the string st.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
  strmanip();
  Console.ReadLine();
}

static void strmanip(){
  string st="C#, C, C++, Java, Python programming";
  string[] arrst = st.Split(' ');
  foreach (string item in arrst)
  Console.WriteLine(item);



                }

      }

}

Insert() method

If you want to insert a substring in to a string, you can use Insert(start_pos, substring) method. The start argument specifies where you want to insert the substring argument in the string. In the example below we insert the substring " tutorial" to the end of the string st and then use the Split() method to split th string.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
  strmanip();
  Console.ReadLine();
}

static void strmanip(){
  string st="C#, C, C++, Java, Python";
  string newst=st.Insert(st.Length, " tutorial");
  Console.WriteLine(newst);
  string[] arrst = st.Split(' ');
  foreach (string item in arrst)
  Console.WriteLine(item);



                }

      }

}

Remove() method

The Remove(start, [char_num.) method enables you to remove an existing substring from a string. The substring with length specified by the char_number argument to be removed starts from the position specified by the start argument. If the char_num argument is not set to a value, the Remove() method will remove characters by starting from the position that is specified by the start argument. In the example below, we use the Remove() method with the IndexOf() method to remove all white spaces from the string st.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
  strmanip();
  Console.ReadLine();
}

static void strmanip(){
  string st="C#, C, C++, Java, Python programming";
  string tempst = "";
  int pos=st.IndexOf(' ');

  while (pos != -1)
 {
   tempst = st.Remove(pos, 1);
   st =tempst;
   pos = st.IndexOf(' ');


}

Console.WriteLine(st);



                }

      }

}

Replace() method

The Replace(old_substring, new_substring) method enables you to replace an existing substring with a new substring in a string. If there are a lot of the same existing substrings in the string, each substring will be replaced by the new substring.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
  strmanip();
  Console.ReadLine();
}

static void strmanip(){


 string st="C#, C, C++, Java, Python tutorial";
 string newst = st.Replace(",", " tutorial");
 Console.WriteLine(newst);


                }

      }

}



HTML Comment Box is loading comments...



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.