May the String Methods of C# be with you
Hello there ! Yes, as you can understand from the title and the beginning, I’ve been lost in the Star Wars universe lately and I’ve been…
May the String Methods of C# be with you
Hello there ! Yes, as you can understand from the title and the beginning, I’ve been lost in the Star Wars universe lately and I’ve been watching Obi wan Kenobi a lot. By the way, I think the person who kept the balance of power for a longer period of time was General Kenobi. Should he deal with Darth Maul, should he deal with General Grievous, should he keep an eye on the Padawans or should he find the Clones? What else should this Jedi do? These alone show that we can say that Kenobi brought balance to the force. :)
Anyway, maybe we can discuss this topic in another article. Let’s now work on String methods to make balancing easier in C#.

www.goodfon.com
These days I do coding exercises from sites like Codewars to improve my algorithm development skills and I noticed that in these types of exercises and also especially in technical interviews, we encounter a lot of string related problems. We may encounter problems here when we do not know the String methods completely or cannot remember them easily. That’s why I decided to write an article that collects and explains String methods. When we need it, both you and I can keep this article handy so we can quickly look at it and remember it.
First of all, it is the String class of the System library that allows us to use methods such as splitting and merging strings.
If you want to examine the String class, I leave the Github link here: ***String Class***
Let’s first see a list of all the String Methods and then go into details about each one.
String Methods of C# List
- Lenght()
- Split()
- Compare()
- Concat()
- Contains()
- EndsWith()
- StartsWith()
- IndexOf();
- LastIndexOf();
- PadLeft()
- PadRight()
- ToUpper()
- ToLower()
- Trim()
- Substring()
- Format()
- Replace()
- Remove()
- Join()
- ToCharArray()
If you want to take a look at more, you can find it here.
Now let’s briefly examine the String methods in detail.
- Lenght()
It is the method used to find the length of a string. Returns the number of characters in a string, including spaces.
Perhaps the most used String method. It is often used to find the number of characters in a string, for example to determine the final step inside for loops.
string text = "Hello there!";
Console.WriteLine(text.Length);
// 12
- Split()
It is used if you want to split a string expression according to a certain condition. For example, these conditions can be; space(“ “), comma(“,”), period(“.”) or a character (“a”).
string text = "May the Force be with you.";
string[] words = text.Split(' '); //separation by space character
foreach (var word in words) {
Console.WriteLine(word);
}
// Return:
// May
// the
// Force
// be
// with
// you.
- Compare()
It is used to compare two strings. There are 3 cases here.
- If 0; two strings are equal to each other.
- If negative, the first string is alphabetically before the second string.
- If positive; the first string is alphabetically after the second string.
string str1 = "Anakin";
string str2 = "Anakin";
string str3 = "Darth Vader";
int result1 = string.Compare(str1, str2);
int result2 = string.Compare(str1, str3);
int result3 = string.Compare(str2, str3);
/*
result1 = 0
result2 = -1
result3 = 1
*/
- Concat()
It is used when you want to combine two or more strings. But if we want to add a space or another character between these words, we can’t do that with Concat. We can do it with Join, which is the method we’ll look at next.
string str1 = "I am one with the Force.";
string str2 = "The Force is with me.";
// strings can also be given as arrays
string[] words = { "I", "am", "one", "with", "the", "Force." "The", "Force", "is", "with", "me" };
string result1= string.Concat(str1, str2);
string result2= string.Concat(words);
/*
result1: "I am one with the Force.The Force is with me."
result2: "IamonewiththeForce.TheForceiswithme."
*/
- Join()
As we mentioned in Concat, it is used if you want to combine multiple strings with a character between them.
string[] planets = { "Coruscant", "Dagobah", "Kamino", "Mustafar", "Naboo"};
string result = string.Join(", ", planets);
//result: Coruscant,Dagobah,Kamino,Mustafar,Naboo
- Contains()
It checks whether a string we specify exists or not. It is a function that returns Boolean.
string text = "When in doubt, go to the source.";
bool result1 = text.Contains("source");
bool result2 = text.Contains("Jedi");
/*
Result1: True
result2: False
*/
It is case sensitive, meaning Hello and hello are perceived differently. If we want to remove case sensitivity, the StringComparison.OrdinalIgnoreCase parameter can be used.
string text = "Hello, world!";
bool result = text.Contains("hello", StringComparison.OrdinalIgnoreCase);
// result : True
- EndsWith()
It is used to check whether a String ends with a specific string character or characters. Returns a Boolean. It is very useful for checking the file type. If you want to ignore case sensitivity, you can use StringComparison.OrdinalIgnoreCase.
string fileName = "KaminoPlanet.txt";
bool result = fileName.EndsWith(".txt");
// result: True
bool result = fileName.EndsWith(".Txt", StringComparison.OrdinalIgnoreCase);
//resutl : False
- StartsWith()
It is very similar to the EndsWith() method. The only difference is that this time it checks whether the String starts with a certain character. This method can also be used to check the file name or the starting characters of a URL.
string url = "https://www.starwars.com";
bool result= url.StartsWith("https");
//result: True
string text= "İstanbul";
bool result= url.StartsWith("İ", StringComparison.CurrentCultureIgnoreCase);
//result: True
Again, this method can be used with StringComparison.OrdinalIgnoreCase, ignoring case sensitivity. But this time we gave an example above for another feature. This feature can be used with the CurrentCultureIgnoreCase method of the StringComparison class for languages that have letters different from English, such as Turkish.
- IndexOf()
This method gives the starting position and index of a character we are looking for in our String, if it exists. If the character we are looking for is not in the sting, it returns -1. The important point here is to find the first place it occurs.
string text = "you were the chosen one!";
int index = text.IndexOf("were");
//result: 4
int index = text.IndexOf("were", 3);
//result: 4
In the second example above, we can enter whichever character we want to start the search with.
- LastIndexOf()
The important point when explaining the IndexOf() method above was that it gives the first occurrence of the searched character. If you want to find the last occurrence of the searched character, the LastIndexOf() method is used.
Likewise, if the character is not in the String, -1 is returned.
string text = "Your weakness is your over-confidence";
int lastIndex = text.LastIndexOf("your", StringComparison.OrdinalIgnoreCase);
// result: 17
int lastIndex = text.LastIndexOf("-", 25);
//result: 0
In the second example above, this time it searches from the given index to the left side.
- PadLeft()
If we have a String but it is not the length we want, if nothing is specified at the beginning of the String, that is, on the Left side, it is filled with a space or a desired character by default, and the desired length is achieved. And of course, the PadLeft() method is used for this.
string text = "3PO";
string paddedText = text.PadLeft(5, 'C-');
//paddedText: 'C-3PO'
Above we wanted the text to be 5 characters long and we wanted to use “C-” at the beginning to pad it.
The original String remains untouched and is assigned to a new variable.
- PadRight()
As with PadLeft, if a fixed length data is requested, this time the end of the String, that is, the right side, can be padded with a space or a character. This time, let’s add a space, which comes by default in the example.
string text = "Anakin";
string paddedText = text.PadRight(5);
//paddedText: 'Anakin '
Again, the original value is left untouched and is assigned to a new variable.
- ToUpper()
This method is used if we want all characters of a String expression to be uppercase. Of course, it doesn’t change the numbers or punctuation marks. Valid for alphabetical characters only. The new value is assigned to a new variable.
string text = "Qui-Gon Jinn";
string result = text.ToUpper();
//result: "QUI-GON JINN"
- ToLower()
As the name suggests, it converts all letters in the String to lowercase. It is the reverse of the ToUpper() method and the same conditions apply.
string text = "PALPATINE";
string result = text.ToLower();
//result: 'palpatine'
- Trim()
Sometimes Strings may have spaces at the beginning and end called WhiteSpace.If these spaces are to be removed, the Trim() method is used. Only the spaces at the beginning and end are removed, the spaces in the middle are left untouched.
string text = " Luke Skywalker ";
string trimmedText = text.Trim();
// trimmedText : 'Luke Skywalker'
Characters other than spaces can also be removed from the beginning and end. It can even be removed by specifying more than one crankcase. Let’s see the examples below;
string text = "---Leia Organa---";
string trimmedText = text.Trim('-');
// trimmedText : 'Leia Organa'
string text = "123Padmé Amidala321";
string trimmedText = text.Trim('1', '2', '3');
// trimmedText : 'Padmé Amidala'
There’s one last thing I want to show you with the trim method. That is with the TrimStart() or TrimEnd() methods. These methods allow the string to be extended by the desired character only from the beginning or only from the end.
string input = "---Din Grogu---";
string trimmedStart = input.TrimStart('-');
//result : 'Din Grogu---'
string trimmedEnd = input.TrimEnd('-');
//result: '---Din Grogu'
- SubString()
If only a certain part of a String value is needed or only a certain part is wanted to be retrieved, the SubString() method is used. The index starts from zero (0).
f the extent to which it will be retrieved is not specified, it will retrieve until the end of the String.
string text = "I have a bad feeling about this";
string result= text.Substring(9, 3);
// result: 'bad'
- Remove()
The Remove() method is used to remove a certain portion from the String. Its usage is similar to the SubString() method. It starts from index class (0). The meaning of the 2nd parameter of this method is that it determines the length of the part to be removed. If not specified, it deletes until the end.
string text = "Fear leads to anger, anger leads to hate, hate leads to suffering.";
string newText = text.Remove(3);
//newText: 'Fear'
- Format()
It is one of the most used String methods. For example, let’s say we want to create a String expression, but we want the expressions in some parts to be dynamic, that is, changeable.For this purpose, placeholders, {0}, {1} and similar structures, are used.
string result = string.Format("Hello, {0}! You are {1} years old.", "John", 30);
//result: 'Hello, John! You are 30 years old.'
The Format() method also supports formats such as currency, date, time. Let’s see examples below.
DateTime today = DateTime.Now;
string formattedDate = string.Format("Today is {0:MMMM dd, yyyy}", today); // Month name and year format
//formattedDate: Today is December 28, 2024
CultureInfo turkishCulture = new CultureInfo("tr-TR");
string.Format("Price: {0:C2}", price); // C2 number in 2 decimal currency format
// result: 1.234,56 ₺
string.Format("The number is: {0:N1}", number); //N1 displays the number with 1 decimal place.
// result: 12.345,68
C : Currency format (₺, $, € etc.).
N : Number format (thousands separators).
*The digit (0, 2, etc.) next to the number or currency determines the number of decimal places.
*It also understands from CultureInfo that the currency is Turkish Liras, for example. That’s why in the example above it adds the ₺, Turkish lira sign.
- Replace()
As the name suggests, it replaces a character or a string of characters with another string of characters. It has 2 parameters. The first parameter is old value. The second parameter is the new value.
Replaces all specified characters in the String, not the first value encountered.
string text = "You are my brother!";
string newText = text.Replace('brother', 'enemy');
//newText: 'You are my enemy!'
string text = "Anakin";
string newText = text.Replace('a', 'o', StringComparison.OrdinalIgnoreCase);
//newText: 'Onokin'
- ToCharArray()
If an operation is desired to be performed on each character of a String, the operation can be performed by converting these characters into a char type array with the ToCharArray() method. Spaces and symbols like ‘-’ are also considered as char array elements. It is a really useful method. Let’s see how to use it below!
string text = "Padawan-Ahsoka Tano";
char[] charArray = text.ToCharArray();
// charArray: ['P','a','d','a','w','a','n','-','A','h','s',,'o','k','a','','T','a','n','o']
string text = "Padawan-Ahsoka Tano";
char[] charArray = text.ToCharArray(8,6);
// charArray: ['A','h','s',,'o','k','a']
Using the parameters of this method, you can specify the character you want to start from and the length of the data. As seen in the second example above, a range of 6 characters long was taken starting from the 8th index.
I think it’s a good list. I hope it will be a very very useful article for you too. If you would like another article on this or another subject, you can specify it in the comments. May the force be with you.
Sources:
https://learn.microsoft.com/en-us/dotnet/api/system.string?view=net-9.0
메타데이터
- post_id
- 99da4e8b34ff
- slug
- may-the-string-methods-of-c-be-with-you-99da4e8b34ff
- url
- https://medium.com/womenintechnology/may-the-string-methods-of-c-be-with-you-99da4e8b34ff
- canonical_url
- https://medium.com/womenintechnology/may-the-string-methods-of-c-be-with-you-99da4e8b34ff
- author_url
- https://medium.com/@zeze-36ze
- status
- ok
- fetched_at
- 2026-07-21 07:40:18