DEV Community

AllCoderThings
AllCoderThings

Posted on

C# String Operations

Originally published at https://allcoderthings.com/en/article/csharp-string-operations

In C#, string is one of the most commonly used data types and represents textual data. Many operations can be performed on strings, such as concatenation, searching, conversion, and formatting. In this article, we will explore basic string methods and useful features with examples.

Defining and Concatenating Strings

Strings are defined inside double quotes. Concatenation can be done with the + operator or with interpolation.

string firstName = "John";
string lastName = "Smith";

string fullName1 = firstName + " " + lastName;
string fullName2 = $"{firstName} {lastName}";

Console.WriteLine(fullName1);
Console.WriteLine(fullName2);
Enter fullscreen mode Exit fullscreen mode

Length and Character Access

The length of a string can be found with the Length property. To access a specific character, use square brackets.

string word = "Hello";
Console.WriteLine(word.Length);  // 5
Console.WriteLine(word[0]);      // H
Enter fullscreen mode Exit fullscreen mode

Substring

To extract a specific part of a string, use the Substring method.

string text = "Programming";
string part = text.Substring(0, 7); // "Program"
Console.WriteLine(part);
Enter fullscreen mode Exit fullscreen mode

Search and Check Operations

There are several methods to search within strings or check for start/end conditions.

string message = "Today the weather is nice";

Console.WriteLine(message.Contains("weather"));     // True
Console.WriteLine(message.StartsWith("Today"));     // True
Console.WriteLine(message.EndsWith("bad"));         // False
Console.WriteLine(message.IndexOf("weather"));      // 6
Enter fullscreen mode Exit fullscreen mode

Uppercase / Lowercase Conversion

To change characters in strings to uppercase or lowercase, use the ToUpper and ToLower methods.

string city = "London";
Console.WriteLine(city.ToUpper()); // LONDON
Console.WriteLine(city.ToLower()); // london
Enter fullscreen mode Exit fullscreen mode

Trim Operations

To remove spaces at the beginning or end of a string, use Trim.

string data = "   Hello   ";
Console.WriteLine(data.Trim());       // "Hello"
Console.WriteLine(data.TrimStart());  // "Hello   "
Console.WriteLine(data.TrimEnd());    // "   Hello"
Enter fullscreen mode Exit fullscreen mode

Replace and Remove

To replace characters or words inside a string, use Replace. To remove a specific part, use Remove.

string text = "C# programming";
Console.WriteLine(text.Replace("C#", "Java")); // Java programming

string remove = "Hello World";
Console.WriteLine(remove.Remove(5)); // "Hello"
Enter fullscreen mode Exit fullscreen mode

Split and Join

To split a string by a specific separator, use Split. To join an array of strings, use Join.

string sentence = "apple,pear,strawberry";
string[] fruits = sentence.Split(',');

foreach (var f in fruits)
    Console.WriteLine(f);

string combined = string.Join(" - ", fruits);
Console.WriteLine(combined);
Enter fullscreen mode Exit fullscreen mode

String Formatting

Strings can be formatted with string.Format or interpolation.

double price = 49.9;
Console.WriteLine(string.Format("Price: {0:C}", price));
Console.WriteLine($"Price: {price:0.00} USD");
Enter fullscreen mode Exit fullscreen mode

Escape Sequences

Escape sequences are used to represent special characters within a string.

  • \n: New line
  • \t: Tab (space)
  • \\: Backslash
  • \": Double quote
  • \': Single quote
string example = "Two\nLines";
string quote = "The teacher said: \"Do your homework this weekend.\"";
Console.WriteLine(example);
Enter fullscreen mode Exit fullscreen mode
// Output:
Two
Lines
The teacher said: "Do your homework this weekend."
Enter fullscreen mode Exit fullscreen mode

Sample Application

Let’s split the words in a sentence entered by the user, count them, and print all the words in uppercase.

Console.Write("Enter a sentence: ");
string sentence = Console.ReadLine();

string[] words = sentence.Split(' ');
Console.WriteLine("Word count: " + words.Length);

foreach (string w in words)
    Console.WriteLine(w.ToUpper());
Enter fullscreen mode Exit fullscreen mode

Top comments (0)