Strings in the C#
Strings in C#
In C#, strings are sequences of characters enclosed in double quotes (""). They are represented by the string keyword and are immutable, meaning their value cannot be changed after creation.
Creating Strings:
string greeting = "Hello, world!";
Accessing Characters:
You can access individual characters using index-based access:
char firstChar = greeting[0]; // 'H'
String Length:
To get the length of a string, use the Length property:
int length = greeting.Length; // 13
String Concatenation:
You can combine strings using the + operator or the Concat method:
string firstName = "Alice";
string lastName = "Johnson";
string fullName = firstName + " " + lastName; // "Alice Johnson"
string fullName2 = string.Concat(firstName, " ", lastName); // "Alice Johnson"
String Comparison:
You can compare strings using the == and != operators, or the Equals method:
string str1 = "Hello";
string str2 = "Hello";
if (str1 == str2)
{
Console.WriteLine("The strings are equal.");
}
if (str1.Equals(str2))
{
Console.WriteLine("The strings are equal.");
}
String Manipulation:
C# provides various methods for manipulating strings:
* Substring: Extracts a portion of a string:
string substring = greeting.Substring(7, 5); // "world"
* IndexOf: Finds the index of a character or substring:
int index = greeting.IndexOf('o'); // 4
* LastIndexOf: Finds the last index of a character or substring:
int lastIndex = greeting.LastIndexOf('o'); // 7
* Replace: Replaces a substring with another:
string newGreeting = greeting.Replace("world", "universe"); // "Hello, universe!"
* ToLower: Converts a string to lowercase:
string lowercaseGreeting = greeting.ToLower(); // "hello, world!"
* ToUpper: Converts a string to uppercase:
string uppercaseGreeting = greeting.ToUpper(); // "HELLO, WORLD!"
* Trim: Removes leading and trailing whitespace:
string trimmedString = " Hello, world! ".Trim(); // "Hello, world!"
String Formatting:
You can format strings using string interpolation or the String.Format method:
int age = 30;
string name = "John";
string formattedString = $"My name is {name} and I am {age} years old.";
string formattedString2 = String.Format("My name is {0} and I am {1} years old.", name, age);
StringBuilder:
For efficient string manipulation, especially when concatenating many strings, use the StringBuilder class:
StringBuilder builder = new StringBuilder();
builder.Append("Hello, ");
builder.Append("world!");
string finalString = builder.ToString();
By understanding these concepts, you can effectively work with strings in your C# applications.
Comments
Post a Comment