String.Replace does not seem to replace brackets with empty string - c#

The following bit of C# code does not seem to do anything:
String str = "{3}";
str.Replace("{", String.Empty);
str.Replace("}", String.Empty);
Console.WriteLine(str);
This ends up spitting out: {3}. I have no idea why this is. I do this sort of thing in Java all the time. Is there some nuance of .NET string handling that eludes me?

The String class is immutable; str.Replace will not alter str, it will return a new string with the result. Try this one instead:
String str = "{3}";
str = str.Replace("{", String.Empty);
str = str.Replace("}", String.Empty);
Console.WriteLine(str);

String is immutable; you can't change an instance of a string. Your two Replace() calls do nothing to the original string; they return a modified string. You want this instead:
String str = "{3}";
str = str.Replace("{", String.Empty);
str = str.Replace("}", String.Empty);
Console.WriteLine(str);
It works this way in Java as well.

Replace actually does not modify the string instance on which you call it. It just returns a modified copy instead.
Try this one:
String str = "{3}";
str = str.Replace("{", String.Empty);
str = str.Replace("}", String.Empty);
Console.WriteLine(str);

Str.Replace returns a new string. So, you need to use it as follows:
String str = "{3}";
str = str.Replace("{", String.Empty);
str = str.Replace("}", String.Empty);

The Replace function returns the modified string, so you have to assign it back to your str variable.
String str = "{3}";
str = str.Replace("{", String.Empty);
str = str.Replace("}", String.Empty);
Console.WriteLine(str);

You'll have to do:
String str = "{3}";
str = str.Replace("{", String.Empty);
str = str.Replace("}", String.Empty);
Console.WriteLine(str);
Look at the String.Replace reference:
Return Value Type: System.String
A String equivalent to this instance but
with all instances of oldValue
replaced with newValue.

I believe that str.Replace returns a value which you must assign to your variable. So you will need to do something like:
String str = "{3}";
str = str.Replace("{", String.Empty);
str = str.Replace("}", String.Empty);
Console.WriteLine(str);

The Replace method returns a string with the replacement. What I think you're looking for is this:
str = str.Replace("{", string.Empty);
str = str.Replace("}", string.Empty);
Console.WriteLine(str);

Besides all of the suggestions so far - you could also accomplish this without changing the value of the original string by using the replace functions inline in the output...
String str = "{3}";
Console.WriteLine(str.Replace("{", String.Empty).Replace("}", String.Empty));

Related

Is there any string.Contains or related method

I am writing a code to if characters from 1 string are present in another string. I used string.Contains but its not solving my case
string str = "abc";
string str2 = "ac";
if(str.Contains(str2))
{
Console.WriteLine("true");
}
I want result to be true. but its not returning true
How about
string str = "abc";
string str2 = "ac";
bool containsAll = !str2.Except(str).Any();
because
I am writing a code to if characters from 1 string are present in another string.
I guess you want to check: " if All characters from 1 string are present in another string."
string str = "abc";
string str2 = "ac";
Console.WriteLine(str2.All(x => str.Contains(x)));

Remove a substring after a substring

I have a string, for example
"blabla{code}<br />blabla{code}<br />bla{code}<br />"
How to remove all entries of <br /> after {code}?
I've tried this:
public string removeBR(string comment)
{
Regex codeRegex = new Regex("{code}<br />", RegexOptions.Singleline);
return codeRegex.Replace(comment, new MatchEvaluator(m =>
{
string value = m.Groups[0].Value;
return value.Remove(value.Length - 6);
}));
}
It works but is there any easier way?
Hope this helps you
string input = "blabla{code}<br />blabla{code}<br />bla{code}<br />";
string output = input.Replace("{code}<br />", "{code}");
Console.WriteLine(output);
as String.Replace returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string.
A simple string.Replace should solve this.
string input = #"blabla{code}<br />blabla{code}<br />bla{code}<br />";
string result = input.Replace("{code}<br />", "{code}");

Linq Read XML with <br> tag

I have a xml file, structure is like following:
<template><body>public DiffSectionType Type<template:br/>{<template:br/><template:tab/>get<template:br/><template:tab/>{<template:br/><template:tab/><template:tab/>return _Type;<template:br/><template:tab/>}<template:br/>}</body></template>
I would like to be more readable, like:
public DiffSectionType Type
{
get
{
return _Type;
}
}
<template:br/> => new line
<template:tab/> => tab
I can read body string, but not able to put it in correct format,
I have tried
var document = XDocument.Load("template.xml");
var body = from element in document.Elements("template").Elements("body")
select element;
foreach(var v in body)
{
Console.WriteLine(v.Value);
}
You could use Regex to solve this so something like this:
string str = #"<template><body>public DiffSectionType Type<template:br/>{<template:br/><template:tab/>get<template:br/><template:tab/>{<template:br/><template:tab/><template:tab/>return _Type;<template:br/><template:tab/>}<template:br/>}</body></template>";
str = Regex.Replace(str, "<template:br\x2F>", Environment.NewLine);
str = Regex.Replace(str, "<template:tab\x2F>", "\t");
str = Regex.Replace(str, "(<\x2Ftemplate>)|(<template>)", "");
str = Regex.Replace(str, "(<\x2Fbody>)|(<body>)", "");

C# Regexp change link format

On my forum I have a lot of redundant link data like:
[url:30l7ypk7]http://www.box.net/shared/0p28sf6hib[/url:30l7ypk7]
In regexp how can I change these to the format:
http://www.box.net/shared/0p28sf6hib
string orig = "[url:30l7ypk7]http://www.box.net/shared/0p28sf6hib[/url:30l7ypk7]";
string replace = "$1";
string regex = #"\[url:.*?](.*?)\[/url:.*?]";
string fixedLink = Regex.Replace(orig, regex, replace);
This isn't doing it totally in Regex but will still work...
string oldUrl = "[url:30l7ypk7]http://www.box.net/shared/0p28sf6hib[/url:30l7ypk7]";
Regex regExp = new Regex(#"http://[^\[]*");
var match = regExp.Match(oldUrl);
string newUrl = string.Format("<a href='{0}' rel='nofollow'>{0}</a>", match.Value);
This should capture the string \[([^\]]+)\]([^[]+)\[/\1\] and group it so you can pull out the URL like this:
Regex re = new Regex(#"\[([^\]]+)\]([^[]+)\[/\1\]");
var s = #"[url:30l7ypk7]http://www.box.net/shared/0p28sf6hib[/url:30l7ypk7]";
var replaced = s.Replace(s, string.Format("{0}", re.Match(s).Groups[1].Value));
Console.WriteLine(replaced)
This is just from memory but I will try to check it over when I have more time. Should help get you started.
string matchPattern = #"\[(url\:\w)\](.+?)\[/\1\]";
String replacePattern = #"<a href='$2' rel='nofollow'>$2</a>";
String blogText = ...;
blogText = Regex.Replace(matchPattern, blogText, replacePattern);

How do I use the Aggregate function to take a list of strings and output a single string separated by a space?

Here is the source code for this test:
var tags = new List<string> {"Portland", "Code","StackExcahnge" };
const string separator = " ";
tagString = tags.Aggregate(t => , separator);
Console.WriteLine(tagString);
// Expecting to see "Portland Code StackExchange"
Console.ReadKey();
Update
Here is the solution I am now using:
var tagString = string.Join(separator, tags.ToArray());
Turns out string.Join does what I need.
For that you can just use string.Join.
string result = tags.Aggregate((acc, s) => acc + separator + s);
or simply
string result = string.Join(separator, tags);
String.Join Method may be?
This is what I use
public static string Join(this IEnumerable<string> strings, string seperator)
{
return string.Join(seperator, strings.ToArray());
}
And then it looks like this
tagString = tags.Join(" ")

Categories