C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: To remove a single character, specify the second parameter as the value 1, which indicates a single char.
C# program that removes chars
using System;
class Program
{
static void Main()
{
//
// Remove the second character from the string.
// This character has the index of 1.
//
const string value1 = "ABC ABC";
string result1 = value1.Remove(1, 1);
//
// Find and remove the first uppercase A from the string.
// This character can occur at any index.
//
const string value2 = "ABC ABC";
string result2 = value2;
int index1 = value2.IndexOf('A');
if (index1 != -1)
{
result2 = value2.Remove(index1, 1);
}
Console.WriteLine(result1);
Console.WriteLine(result2);
}
}
Output
AC ABC
BC ABC
First: RemoveQuotes1 allocates a char array. It creates a string from all non-quote characters from the source string.
Second: The second method, RemoveQuotes2, is much shorter and simply replaces a quotation mark with the empty string literal.
Result: The first method, RemoveQuotes1, was much faster. It can act upon individual characters and not strings.
Method that removes char by value with loop: C#
static string RemoveQuotes1(string input)
{
int index = 0;
char[] result = new char[input.Length];
for (int i = 0; i < input.Length; i++)
{
if (input[i] != '"')
{
result[index++] = input[i];
}
}
return new string(result, 0, index);
}
Method that removes char by value with Replace: C#
static string RemoveQuotes2(string input)
{
return input.Replace("\"", "");
}
Benchmark details
RemoveQuotes1("Thanks for \"visiting\"!");
RemoveQuotes2("Thanks for \"visiting\"!");
Benchmark results
105.75 ns
240.84 ns
Instead: If you want to Replace characters, specify the characters as strings and use an empty string literal as the second parameter.
ReplaceTip: In this example, you could use Substring instead of Remove with no functional difference.