Different Type of String Operations in .NET using C#
In .NET C#, there are several types of string operations like – calculate length, substring operations, case change, replace, character array, string array. There are already predefined functions available for these operations. You just need to use those by following the rules.
In this tutorial, You are going to learn some popular operations of string in C# programming. Let’s discuss some operations with examples:
Convert CSV file to TXT file in DOT NET using vb (windows form)
Count the length of a string
In the example below, we are counting the length of the string:
string str = "Welcome to Codespeedy"; Console.WriteLine(str.Length);
Output:
Length of the string:21
As you can see from the output, it returns the length of the characters from the string.
Find substring from a given string
Here is another example, where I am searching if a substring present in the string or not:
string str = "Welcome to Codespeedy"; string result1 = str.Substring(11); //Define only starting position. Print data from starting position to end of string string result2 = str.Substring(0, 7); //Define starting position, lentgh. Print data of that length from starting given position. Console.WriteLine(result1); Console.WriteLine(result2);
Output:
Codespeedy Welcome
Change case of a string
You can also change the case of a string. You can convert all the characters of the string to lowercase using ToLower()
method or to uppercase using the ToUpper()
method. Below is shown an example:
string str = "Welcome to Codespeedy"; Console.WriteLine(str.ToLower()); //Convert to Lower case letter Console.WriteLine(str.ToUpper()); //Convert to Upper case letter
Output:
welcome to codespeedy WELCOME TO CODESPEEDY
Replace character of a string
Here we will replace an old character with a new character in the given string using the Replace()
method:
string str = "Welcome to Codespeedy"; Console.WriteLine(str.Replace('s', 'S'));
Output:
Welcome to CodeSpeedy
Convert string to a character array
Here we will convert a string to an array of characters
string str = "Welcome to Codespeedy"; char[] c = str.ToCharArray(); foreach (char item in c) { Console.WriteLine(item); }
Output:
W e l c o m e t o C o d e s p e e d y
Store a string to string array
Here we will store a string into an array of strings. We will use space as the separator and break the string into parts:
string str = "Welcome to Codespeedy"; string[] res1 = str.Split(' '); //Split the string into different parts by seperator blankspace foreach (string item in res1) { Console.WriteLine(item); }
Output:
Welcome to Codespeedy
Leave a Reply