Replace multiple characters in a C# string
You can use a replace regular expression.
s/[;,\t\r ]|[\n]{2}/\n/g
s/
at the beginning means a search- The characters between
[
and]
are the characters to search for (in any order) - The second
/
delimits the search-for text and the replace text
In English, this reads:
"Search for ;
or ,
or \t
or \r
or (space) or exactly two sequential
\n
and replace it with \n
"
In C#, you could do the following: (after importing System.Text.RegularExpressions
)
Regex pattern = new Regex("[;,\t\r ]|[\n]{2}");
pattern.Replace(myString, "\n");
Replace Multiple String Elements in C#
Quicker - no. More effective - yes, if you will use the StringBuilder
class. With your implementation each operation generates a copy of a string which under circumstances may impair performance. Strings are immutable objects so each operation just returns a modified copy.
If you expect this method to be actively called on multiple Strings
of significant length, it might be better to "migrate" its implementation onto the StringBuilder
class. With it any modification is performed directly on that instance, so you spare unnecessary copy operations.
public static class StringExtention
{
public static string clean(this string s)
{
StringBuilder sb = new StringBuilder (s);
sb.Replace("&", "and");
sb.Replace(",", "");
sb.Replace(" ", " ");
sb.Replace(" ", "-");
sb.Replace("'", "");
sb.Replace(".", "");
sb.Replace("eacute;", "é");
return sb.ToString().ToLower();
}
}
Replace Multiple Characters in string
You cannot use Replace because it works its replacement operation on the whole string, not char by char.
A simple brute force solution could be this one
void Main()
{
// A dictionary where every key points to its replacement char
Dictionary<char, char> replacements = new Dictionary<char, char>()
{
{'(', ')'},
{')', '('},
};
string source = ")Hi(";
StringBuilder sb = new StringBuilder();
foreach (char c in source)
{
char replacement = c;
if(replacements.ContainsKey(c))
replacement = replacements[c];
sb.Append(replacement,1);
}
Console.WriteLine(sb.ToString());
}
You can transform this in an extension method adding to a static class
public static class StringExtensions
{
public static string ProgressiveReplace(this string source, Dictionary<char, char> replacements)
{
StringBuilder sb = new StringBuilder();
foreach (char c in source)
{
char replacement = c;
if (replacements.ContainsKey(c))
replacement = replacements[c];
sb.Append(replacement, 1);
}
return sb.ToString();
}
}
and call it from your code with
Dictionary<char, char> replacements = new Dictionary<char, char>()
{{'(', ')'},{')', '('}};
s = s.ProgressiveReplace(replacements);
Replacing multiple characters in a string in c# by a one liner
You can use Regex.Replace
:
string output = Regex.Replace(input, "[$|&]", " ");
Replace multiple characters in a string with different characters
Since you mentioned in comment that the data originally came from dictionary, you could loop through the dictionary and format the data as you like.
Sample code with Dictionary<string, object>
:
var dict = new Dictionary<string, object>();
dict.Add("key1", 1);
dict.Add("key2", "string");
dict.Add("key3", true);
dict.Add("key4", new DateTime(2020, 1, 1));
foreach (KeyValuePair<string, object> kv in dict) {
Console.WriteLine(string.Format("{0}={1}", kv.Key, kv.Value.ToString()));
}
Alternative to multiple String.Replaces
For an 'easy' alternative just use a StringBuilder....
StringBuilder sb = new StringBuilder("11223344");
string myString =
sb
.Replace("1", string.Empty)
.Replace("2", string.Empty)
.Replace("3", string.Empty)
.ToString();
Find and Replace multiple strings in c# with or without regex
I think you just need String.Replace
in a loop:
public static string Highlitor(string text, IEnumerable<string> replaceStrings)
{
string result = text;
foreach(string repl in replaceStrings.Distinct())
{
string replWith = string.Format("<span class='highlight-text'>{0}</span>", repl);
result = result.Replace(repl, replWith);
}
return result;
}
You don't need Distinct
if the list doesn't contain duplicates.
UPDATE: as it seems things are much more complicated. You want to replace parts by preserving the original case when the pattern is part of the final replacement string.
Here is a modified version of my above method that uses an extended version of String.Replace
:
public static string Highlitor(string text, IEnumerable<string> replaceStrings)
{
string result = text;
foreach (string repl in replaceStrings.Distinct())
{
string replWith = string.Format("<span class='highlight-text'>{0}</span>", repl);
result = ReplaceCaseInsensitive(result, repl, replWith, true);
}
return result;
}
Here is the method that replaces strings case-insensitively and supports keeping the original case:
public static string ReplaceCaseInsensitive(string original, string pattern, string replacement, bool keepOriginalCase = false)
{
int count, position0, position1;
count = position0 = position1 = 0;
int replacementIndexOfPattern = replacement.IndexOf(pattern, StringComparison.OrdinalIgnoreCase);
if (replacementIndexOfPattern == -1)
keepOriginalCase = false; // not necessary
int inc = (original.Length / pattern.Length) *
(replacement.Length - pattern.Length);
char[] chars = new char[original.Length + Math.Max(0, inc)];
bool[] upperCaseLookup = new bool[pattern.Length];
while ((position1 = original.IndexOf(pattern, position0, StringComparison.OrdinalIgnoreCase)) != -1)
{
// first part that will not be replaced
for (int i = position0; i < position1; ++i)
chars[count++] = original[i];
// remember the case of each letter in the found patter that will be replaced
if (keepOriginalCase)
{
for (int i = 0; i < pattern.Length; ++i)
upperCaseLookup[i] = Char.IsUpper(original[position1 + i]);
}
// The part that will be replaced:
for (int i = 0; i < replacement.Length; ++i)
{
// only keep case of the relevant part of the replacement that contains the part to be replaced
bool lookupCase = keepOriginalCase
&& i >= replacementIndexOfPattern
&& i < replacementIndexOfPattern + pattern.Length;
char newChar = replacement[i];
if (lookupCase)
{
bool wasUpper = upperCaseLookup[i - replacementIndexOfPattern];
bool isUpper = Char.IsUpper(newChar);
if (wasUpper && !isUpper)
newChar = Char.ToUpperInvariant(newChar);
else if (!wasUpper && isUpper)
newChar = Char.ToLowerInvariant(newChar);
}
else
{
newChar = replacement[i];
}
chars[count++] = newChar;
}
position0 = position1 + pattern.Length;
}
if (position0 == 0)
return original;
// the rest
for (int i = position0; i < original.Length; ++i)
chars[count++] = original[i];
return new string(chars, 0, count);
}
It's algorithm based on: Fastest C# Case Insenstive String Replace.
Replace multiple characters in C# using .replace without creating a loop
Before going to the answer let me describe what went wrong in your case, Actually the replace operations returns a new instance of the string so after the first replace(t1.Replace('A','B')
the resulting string becomes BBCD
(A
is replaced with B
) and you are performing the next replace operation in this string, hence every B
will be replaced with C
. so before final Replace your input string becomes DDDD
.
I've a simple solution using LINQ with String.Join, You can take a look into the working example here
string inputString = "ABCD";
var ReplacedString = String.Join("", inputString.Select(x => x == 'A' ? 'B' :
x == 'B' ? 'C' :
x == 'C' ? 'D' :
x == 'D' ? 'E' :
x));
Replace multiple words in string
If you're planning on having a dynamic number of replacements, which could change at any time, and you want to make it a bit cleaner, you could always do something like this:
// Define name/value pairs to be replaced.
var replacements = new Dictionary<string,string>();
replacements.Add("<Name>", client.FullName);
replacements.Add("<EventDate>", event.EventDate.ToString());
// Replace
string s = "Dear <Name>, your booking is confirmed for the <EventDate>";
foreach (var replacement in replacements)
{
s = s.Replace(replacement.Key, replacement.Value);
}
Replacing Multiple Chars to Multiple values in a String in C#
application only takes the last Replace method (Z to G)
This is because string
s are immutable. More importantly, your algorithm is broken, because subsequent substitutions "see" the results of the previous ones. You cannot do the replacements sequentially - if you want to get correct results, you must consider them all at once. Otherwise, l
will become o
, even though your algorithm replaces l
with n
:
// Let's say the text is "Hello"
text = text.replace('l', 'n'); // The text becomes "Henno"
... // More substitutions
text = text.replace('n', 'o'); // The text becomes "Heooo"
Here is how you can fix it:
StringBuilder res = new StringBuilder();
foreach (char c in txt1.Text) {
char toAppend;
switch (c) {
case 'I': toAppend = 'L'; break;
case 'j': toAppend = 'n'; break;
case 'J': toAppend = 'N'; break;
case 'k': toAppend = 'l'; break;
...
default: toAppend = '?';
}
res.append(toAppend);
}
Related Topics
How to Show Progress Bar for Upload with Ftpwebrequest
Setting the User-Agent Header for a Webclient Request
Most Elegant Xml Serialization of Color Structure
Difference Between Invoke and Dynamicinvoke
Can You Get the Column Names from a SQLdatareader
Which Is Better, Return Value or Out Parameter
Sqlite Database Locked Exception
Transparent Images with C# Winforms
Databinding to List - See Changes of Data Source in Listbox, Combobox
Null or Default Comparison of Generic Argument in C#
Serialize Dictionary as Array (Of Key Value Pairs)
Console Application Closes Immediately After Opening in Visual Studio