Different Type of String Operations in .NET using C#
In .NET there are several types of string operations like – calculate length, substring operations, case change, replace, character array, string array. There are already predefined functions for these operations. Just we need to use it in the proper place.
In this post, we are going to discuss some popular operations of string. We will learn the following things with the proper example so that it becomes easier to understand for learners.
Convert CSV file to TXT file in DOT NET using vb (windows form)
Count the length of a string
Here we will count the length of the total string including blank space.
string str = "Welcome to Codespeedy"; Console.WriteLine(str.Length);
Output:
Length of the string:21
Find substring from a given string
Here we will find any particular portion from a given string.
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
Here we will convert the string to UPPER case and LOWER case
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
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.
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
N.B.: For code in vb please leave comment
Leave a Reply