String

String

In C#, a string is a sequence of characters, represented by the string keyword. Here are some of the most commonly used methods for working with strings:

  1. Length: Returns the number of characters in a string.
				
					string str = "Hello, World!";
int len = str.Length; // len = 13

				
			
  1. Substring: Returns a substring from the specified starting position and length.
				
					string str = "Hello, World!";
string substr = str.Substring(7, 5); // substr = "World"

				
			
  1. IndexOf: Returns the index of the first occurrence of a specified character or substring within a string.
				
					string str = "Hello, World!";
int index = str.IndexOf("World"); // index = 7

				
			
  1. Replace: Returns a new string in which all occurrences of a specified character or substring are replaced with another character or substring.
				
					string str = "Hello, World!";
string newStr = str.Replace("World", "Universe"); // newStr = "Hello, Universe!"

				
			
  1. ToLower: Returns a new string in which all characters are converted to lowercase.
				
					string str = "Hello, World!";
string newStr = str.ToLower(); // newStr = "hello, world!"

				
			
  1. ToUpper: Returns a new string in which all characters are converted to uppercase.
				
					string str = "Hello, World!";
string newStr = str.ToUpper(); // newStr = "HELLO, WORLD!"

				
			
  1. Concat: Concatenates two or more strings into a single string.
				
					string str1 = "Hello, ";
string str2 = "World!";
string newStr = String.Concat(str1, str2); // newStr = "Hello, World!"

				
			
  1. Format: Replaces one or more format items in a string with the string representation of a specified object.
				
					string str = "Hello, {0}!";
string name = "John";
string newStr = String.Format(str, name); // newStr = "Hello, John!"

				
			

These are just a few of the many methods provided by the String class in C#. The exact method you need will depend on the specific program you’re writing.

Join To Get Our Newsletter
Spread the love