C# Replace(), Trim(), Split(), Substring(), IndexOf(), LastIndexOf() functions

Directory

1. Replace()

2. Trim()

3. Split()

4. Substring()

5. IndexOf()

6. LastIndexOf()


1. Replace()

In C#, Replace() is a string method used to replace a specified character or substring with another character or string. The following are some common usages and sample codes of the Replace() method:

  1. Replace one character in a string with another
    string original = "Hello World";
    string replaced = original.Replace('o', '0');
    Console.WriteLine(replaced); // Output: Hell0 W0rld
    

    You can use the Replace() method to remove spaces Use the String.Replace() method to replace spaces with empty strings:

    string str = " This is a string with spaces. ";
    str = str.Replace(" ", "");
    Console. WriteLine(str);
    

    remove all spaces

  2. Replace a substring in a string with another string
    string original = "The quick brown fox jumps over the lazy dog";
    string replaced = original.Replace("fox", "cat");
    Console.WriteLine(replaced); // Output: The quick brown cat jumps over the lazy dog
    
  3. Use a regular expression in the string to replace the matched content
    string original = "Hello, World!";
    string replaced = Regex.Replace(original, "[aeiou]", "*");
    Console.WriteLine(replaced); // output: H*ll*, W*rld!
    

    In this example, use the regular expression [aeiou] to match any single vowel in the string and replace the matched content with *.

    It should be noted that the Replace() method returns a new string, rather than modifying the original string.

2. Trim()

The Trim() method in C# is used to remove blank characters at the beginning and end of a string, including spaces, tabs, and newlines. It returns a new string that is a copy of the original string but with leading and trailing whitespace characters removed.

Here are some examples using the Trim() method:

string str1 = "Hello World! ";
string str2 = "\t\tHello World!\t\t";
string str3 = "\\
\\
Hello World!\\
\\
";

// Use the Trim method to remove leading and trailing whitespace characters
string trimmed1 = str1. Trim();
string trimmed2 = str2. Trim();
string trimmed3 = str3. Trim();

Console.WriteLine(trimmed1); // "Hello World!"
Console.WriteLine(trimmed2); // "Hello World!"
Console.WriteLine(trimmed3); // "Hello World!"

In the above example, we defined three strings containing whitespace characters, and used the Trim() method to remove whitespace characters at the beginning and end of them respectively. In the output, we can see the string after removing whitespace characters.

In addition to the Trim() method, there are several other similar methods in C#, such as TrimStart() and TrimEnd(). The TrimStart() method is used to remove blank characters at the beginning of the string, and the TrimEnd() method is used to remove blank characters at the end of the string. These methods also return a new string that is a copy of the original string, but with whitespace characters removed at the specified positions.

3. Split()

The Split() method in C# is used to split a string into a string array according to the specified delimiter. It can accept one or more delimiters, and it can be specified whether to ignore blank entries.

Here are some examples using the Split() method:

string str = "apple,banana,orange";

// Separate the strings with commas and save the result in an array of strings
string[] arr1 = str. Split(',');

// output each element in the array
foreach (string item in arr1)
{
    Console. WriteLine(item);
}

// use multiple delimiters
string str2 = "apple|banana-orange";
string[] arr2 = str2.Split(new char[] { '|', '-' });

// output each element in the array
foreach (string item in arr2)
{
    Console. WriteLine(item);
}

// ignore blank items
string str3 = "apple,banana,,orange";
string[] arr3 = str3.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

// output each element in the array
foreach (string item in arr3)
{
    Console. WriteLine(item);
}

The result of running the above example is as follows:

apple
banana
orange
apple
banana
orange
apple
banana
orange

The first example divides the original string into 3 strings separated by commas, which are “apple”, “banana” and “orange”, and then outputs them to the console.

The second example divides the original string into 3 strings according to the ‘|’ and ‘-‘ delimiters, and outputs them to the console as well.

The third example adds a blank entry to the original string and uses the StringSplitOptions.RemoveEmptyEntries option to ignore the blank entry, resulting in the same result as the first example.

In the above example, we first defined a string containing multiple fruit names, and then split it into an array of strings using a comma delimiter. Next, we demonstrate how to use multiple delimiters and ignore blank entries.

It should be noted that the Split() method returns an array of strings. If the original string does not contain delimiters, the Split() method returns a string array containing only the original string.

4. Substring()

The Substring() method in C# is used to extract a substring of a specified length from a string. It has two overloads, one that takes a start index and a length as arguments, and the other that takes a start index and returns all characters from that index to the end of the string.

Here are some examples using the Substring() method:

string str = "Hello, world!";

// Extract 3 characters starting from index 6
string sub1 = str. Substring(6, 3);
Console.WriteLine(sub1); // "wor"

// Extract all characters from index 7 to the end of the string
string sub2 = str. Substring(7);
Console.WriteLine(sub2); // "world!"

In the above example, we first defined a string containing “Hello, world!”. We then use the Substring() method to extract 3 characters starting from index 6 and save the result into the sub1 string variable. Next, we use the Substring() method to extract all the characters from index 7 to the end of the string and save the result into the sub2 string variable. Finally, we output these two substrings to the console.

It should be noted that the Substring() method returns a new string, and the original string has not been modified. If the specified start index is outside the range of the string, or if the specified length exceeds the number of characters from the start index to the end of the string, the Substring() method will throw an ArgumentOutOfRangeException.

5. IndexOf()

The IndexOf() method in C# is used to find a specified character or substring in a string, and return the position index of the first occurrence. It has multiple overloaded versions, which can specify parameters such as the starting index of the search and the search direction.

Here are some examples using the IndexOf() method:

string str = "The quick brown fox jumps over the lazy dog.";

// Find the first occurrence of the string "fox"
int index1 = str.IndexOf("fox");
Console. WriteLine(index1); // 16

// Find the first occurrence of the string "fox" starting from index 20
int index2 = str.IndexOf("fox", 20);
Console. WriteLine(index2); // -1

// Find the first occurrence of the string "fox" from index 20 forward
int index3 = str.IndexOf("fox", 20, StringComparison.CurrentCultureIgnoreCase);
Console. WriteLine(index3); // 16

In the example above, we first defined a string containing “The quick brown fox jumps over the lazy dog.”. Then, we use the IndexOf() method to find the first occurrence of the string “fox” and store the result in the index1 variable. Next, we use the IndexOf() method to find the first occurrence of the string “fox” starting from index 20, and save the result to the index2 variable. Since “fox” does not appear in the substring starting at index 20, the return value is -1. Finally, we use the IndexOf() method to find the first occurrence of the string “fox” from index 20 forward, and save the result to the index3 variable. Since the string “fox” occurs in the substring starting at index 16, the return value is 16.

It should be noted that the IndexOf() method returns the position index of the first occurrence, and -1 will be returned if the specified character or substring does not exist in the string. In addition, the IndexOf() method is case-sensitive by default. If you want to perform a case-insensitive search, you can use parameters such as StringComparison.OrdinalIgnoreCase or StringComparison.CurrentCultureIgnoreCase.

6. LastIndexOf()

The LastIndexOf() method in C# is similar to the IndexOf() method, which is also used to find a specified character or substring in a string and return the index of the last occurrence. It also has multiple overloaded versions, which can specify parameters such as the starting index of the search and the search direction.

Here are some examples using the LastIndexOf() method:

string str = "The quick brown fox jumps over the lazy dog.";

// Find the last occurrence of the string "fox"
int index1 = str.LastIndexOf("fox");
Console. WriteLine(index1); // 16

// Find the last occurrence of the string "fox" starting from index 20
int index2 = str.LastIndexOf("fox", 20);
Console. WriteLine(index2); // -1

// Find the last occurrence of the string "fox" starting from index 20
int index3 = str.LastIndexOf("fox", 20, StringComparison.CurrentCultureIgnoreCase);
Console. WriteLine(index3); // 16

In the above example, we used the LastIndexOf() method to find the last occurrence of the string “fox”, and specified different starting index and search direction parameters. The rest of the usage is similar to the IndexOf() method.

It should be noted that the LastIndexOf() method returns the position index of the last occurrence, and -1 will be returned if the specified character or substring does not exist in the string. In addition, the LastIndexOf() method is case-sensitive by default. If you want to perform a case-insensitive search, you can use parameters such as StringComparison.OrdinalIgnoreCase or StringComparison.CurrentCultureIgnoreCase.