C# String Replace

C# string replace

Try this:

line.Replace("\",\"", ";")

C# String Replace safely

You could replace the longest strings first, f.e. with this method:

public static string ReplaceSafe(string str, IEnumerable<KeyValuePair<string, string>>  replaceAllOfThis)
{
foreach (var kv in replaceAllOfThis.OrderByDescending(kv => kv.Key.Length))
{
str = str.Replace(kv.Key, kv.Value);
}
return str;
}

Your example:

Example = ReplaceSafe(Example, new[] {new KeyValuePair<string, string>("OK", "true"), new KeyValuePair<string, string>("LOK", "false")});

c# replace string with many x

You can create a new string of "x" repeated the number of characters in your word. No need for regexes.

word.Text = new string('x', word.Text.Length);

C# How to replace the variables inside strings

You can try to Replace all {...} with a help of Regular Expressions:

  using System.Text.RegularExpressions;

...

// All possible substitutions (from database?)
Dictionary<string, string> replacements =
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) {
{ "name", "name1"},
{ "country", "country1"},
};

string greet = "Hi {name}, Are you from {country}";

string result = Regex.Replace(
greet,
@"(?<=\{).*?(?=\})",
match => replacements.TryGetValue(match.Value, out var value) ? value : "???");

Replace \\ with \ in a string in C#

I suspect your string already actually only contains a single backslash, but you're looking at it in the debugger which is escaping it for you into a form which would be valid as a regular string literal in C#.

If print it out in the console, or in a message box, does it show with two backslashes or one?

If you actually want to replace a double backslash with a single one, it's easy to do so:

text = text.Replace(@"\\", @"\");

... but my guess is that the original doesn't contain a double backslash anyway. If this doesn't help, please give more details.

EDIT: In response to the edited question, your stringToBeReplaced only has a single backslash in. Really. Wherever you're seeing two backslashes, that viewer is escaping it. The string itself doesn't have two backslashes. Examine stringToBeReplaced.Length and count the characters.

How to replace characters in a string in c#

Something like:

String dna="ACTG";
String dnaComplement = "";

foreach(char c in dna)
{
if (c == 'A') dnaComplement += 'T';
else if (c == 'C') dnaComplement += 'G';
// and so long
}

String.Replace() is not working as expected to replace weird chars in strings in C#

Change this:

DisplayName.Replace("'", "-").Replace("\"", "-");

To this:

DisplayName = DisplayName.Replace("'", "-").Replace("\"", "-");


Related Topics



Leave a reply



Submit