05 Feb C# String Operations
We will perform the following operations on strings in C#:
- Concatenate Strings
- String length
- Convert string to uppercase
- Convert string to lowercase
- Access a character using the index number
Concatenate strings
To concatenate strings in C#, use the + operator. In the below example, we have concatenated two strings:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
using System; namespace Demo { class Studyopedia { static void Main(string[] args) { // string variable 1 and variable 2 string str1, str2; str1 = "Amit"; str2 = "Thinks"; // Display string channel_name = str1 + str2; Console.WriteLine("Channel = {0}", channel_name); } } } |
Output
1 2 3 |
Channel = AmitThinks |
String Length
To get the length of a String, use the Length property in C#. Let us see an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; namespace Demo { class Studyopedia { static void Main(string[] args) { // string variable string s = "Demo"; Console.WriteLine("My String = {0}", s); Console.WriteLine("String Length = {0}", s.Length); } } } |
Output
1 2 3 4 |
My String = Demo String Length = 4 |
Convert string to uppercase
Use the ToUpper() method to convert the string to uppercase in C#. Let us see an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
using System; namespace Demo { class Studyopedia { static void Main(string[] args) { // The string variable string s = "Amit Diwan"; // Display the string Console.WriteLine("My String = {0}", s); // String converted to uppercase Console.WriteLine("Uppercase = {0}", s.ToUpper()); } } } |
Output
1 2 3 4 |
My String = Amit Diwan Uppercase = AMIT DIWAN |
Convert string to lowercase
Use the ToLower() method to convert the string to lowercase in C#. Let us see an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
using System; namespace Demo { class Studyopedia { static void Main(string[] args) { // The string variable string s = "AMIT DIWAN"; // Display the string Console.WriteLine("My String = {0}", s); // String converted to lowercase Console.WriteLine("Lowercase = {0}", s.ToLower()); } } } |
Output
1 2 3 4 |
My String = AMIT DIWAN Lowercase = amit diwan |
Access a character using the index number
The index number begins with 0, therefore 1st position is at the 0th index. We will access a character using the index number. Let us see an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
using System; namespace Demo { class Studyopedia { static void Main(string[] args) { // The string variable string s = "AMIT DIWAN"; // Display the string Console.WriteLine("My String = {0}", s); // Access a character at 2th position i.e. 1st index Console.WriteLine("Character = {0}", s[1]); } } } |
Output
1 2 3 4 |
My String = AMIT DIWAN Character = M |
No Comments