I am trying to remove all of a specific character from a string. I have been using String.Replace, but it does nothing, and I don't know why. This is my current code:
if (Gamertag2.Contains("^"))
{
Gamertag2.Replace("^" + 1, "");
}
This just leaves the string as it was before. Can anyone please explain to me as to why?
You must assign the return value of String.Replace to your original string instance:
hence instead of(no need for the Contains check)
if (Gamertag2.Contains("^"))
{
Gamertag2.Replace("^" + 1, "");
}
just this(what's that mystic +1?):
Gamertag2 = Gamertag2.Replace("^", "");
Two things:
1) C# Strings are immutable. You'll need to do this :
Gamertag2 = Gamertag2.Replace("^" + 1, "");
2) "^" + 1? Why are you doing this? You are basically saying Gamertag2.Replace("^1", ""); which I'm sure is not what you want.
Like climbage said, your problem is definitely
Gamertag2.Replace("^"+1,"");
That line will only remove instances of "^1" from your string. If you want to remove all instances of "^", what you want is:
Gamertag2.Replace("^","");
I know this thread is old and also that my solution may be inefficient to the extreme, but it replaces all occurrences of a string. Found that if I was looking for "\r\n\r\n\r\n" to replace with "\r\n\r\n" a single Replace() didn't catch all.
Therefor this:
do // First get rid of spaces like " \r"
{
str = str.Replace(" \r","\r")
} while (str.Cointains(" \r"));
do // Then remove the CrLf's in surplus.
{
str = str.Replace("\r\n\r\n\r\n","\r\n\r\n")
} while (str.Cointains("\r\n\r\n\r\n"));
Related
From a string, check if it starts with a value 'startsWithCorrectId'...if it does remove the value from the start. Problem being if this value is also found again in the string, it will also remove it. I realise this is what .replace does...but is there something like .startsWith to RemoveAtStart?
string startsWithCorrectId = largeIconID.ToString();
//startsWithCorrectId will be '1'
string fullImageName = file.Replace("_thumb", "");
//fullImageName will be "1red-number-1.jpg"
//file will be '1red-number-1_thumb.jpg'
if(file.StartsWith(startsWithCorrectId))
{
fullImageName = fullImageName.Replace(startsWithCorrectId, "");
//so yes this is true but instead of replacing the first instance of '1'..it removes them both
}
Really what I would like is for '1red-number-1.jpg' to become 'red-number-1.jpg'....NOT 'red-number-.jpg'..replacing all instances of 'startsWithCorrectId' I just want to replace the first instance
One solution is to use Regex.Replace():
fullImageName = Regex.Replace(fullImageName, "^" + startsWithCorrectId, "");
This will remove startsWithCorrectId if it's at the start of the string
if(file.StartsWith(startsWithCorrectId))
{
fullImageName = fullImageName.SubString(startsWithCorrectId.Length);
}
if I have undestood your correctly you would need to get a string starting from correctId.Length position
if(fullImageName .StartsWith(startsWithCorrectId))
fullImageName = fullImageName .Substring(startsWithCorrectId.Length);
if you like extensions:
public static class StringExtensions{
public static string RemoveFirstOccuranceIfMatches(this string content, string firstOccuranceValue){
if(content.StartsWith(firstOccuranceValue))
return content.Substring(firstOccuranceValue.Length);
return content;
}
}
//...
fullImageName = fullImageName.RemoveFirstOccuranceIfMatches(startsWithCorrectId);
You can do so with a regular expression where you can encode the requirement that the string starts at the beginning:
var regex = "^" + Regex.Escape(startsWithCorrectId);
// Replace the ID at the start. If it doesn't exist, nothing will change in the string.
fullImageName = Regex.Replace(fullImageName, regex, "");
Another option is to use a substring, instead of a replace operation. You already know that it's at the start of the string, you can just take the substring starting right after it:
fullImageName = fullImageName.Substring(startsWithCorrectId.Length);
Example String
This is an important example about regex for my work.
I can extract important example about regex with this (?<=an).*?(?=for) snippet. Reference
But i would like to extract to string right to left side. According to this question's example; first position must be (for) second position must be (an).
I mean extracting process works back ways.
I tried what i want do as below codes in else İf case, but it doesn't work.
public string FnExtractString(string _QsString, string _QsStart, string _QsEnd, string _QsWay = "LR")
{
if (_QsWay == "LR")
return Regex.Match(_QsString, #"(?<=" + _QsStart + ").*?(?=" + _QsEnd + ")").Value;
else if (_QsWay == "RL")
return Regex.Match(_QsString, #"(?=" + _QsStart + ").*?(<=" + _QsEnd + ")").Value;
else
return _QsString;
}
Thanks in advance.
EDIT
My real example as below
#Var|First String|ID_303#Var|Second String|ID_304#Var|Third String|DI_t55
When i pass two string to my method (for example "|ID_304" and "#Var|") I would like to extract "Second String" but this example is little peace of my real string and my string is changeable.
No need for forward or backward lookahead! You could just:
(.*)\san\s.*\sfor\s
The \s demands whitespace, so you don't match an import*an*t.
One potential problem in your current solution is that the string passed in contains special characters, which needs to be escaped with Regex.Escape before concatenation:
return Regex.Match(_QsString, #"(?<=" + Regex.Escape(_QsStart) + ").*?(?=" + Regex.Escape(_QsEnd) + ")").Value;
For your other requirement of matching RL, I don't understand your requirement.
If I have the following string:
/lorem/ipsum/dolor
and I want this to become:
/lorem/ipsum
What is the short-hand way of removing the last forward slash, and all characters following it?
I know how I can do this by spliting the string into a List<> and removing the last item, and then joining, but is there a shorter way of writing this?
My question is not URL specific.
You can use Substring() and LastIndexOf():
str = str.Substring(0, str.LastIndexOf('/'));
EDIT (suggested comment)
To prevent any issues when the string may not contain a /, you could use something like:
int lastSlash = str.LastIndexOf('/');
str = (lastSlash > -1) ? str.Substring(0, lastSlash) : str;
Storing the position in a temp-variable would prevent the need to call .LastIndexOf('/') twice, but it could be dropped in favor of a one-line solution instead.
If there is '/' at the end of the url, remove it.
If not; just return the original one.
var url = this.Request.RequestUri.ToString();
url = url.EndsWith("/") ? url.Substring(0, url.Length - 1) : url;
url += #"/mycontroller";
You can do something like str.Remove(str.LastIndexOf("/")), but there is no built-in method to do what you want.
Edit: you could also use the Uri object to traverse directories, although it does not give exactly what you want:
Uri baseUri = new Uri("http://domain.com/lorem/ipsum/dolor");
Uri myUri = new Uri(baseUri, ".");
// myUri now contains http://domain.com/lorem/ipsum/
One simple way would be
String s = "domain.com/lorem/ipsum/dolor";
s = s.Substring(0, s.LastIndexOf('/'));
Console.WriteLine(s);
Another maybe
String s = "domain.com/lorem/ipsum/dolor";
s = s.TrimEnd('/');
Console.WriteLine(s);
You can use the regex /[^/]*$ and replace with the empty string:
var fixed = new Regex("/[^/]*$").Replace("domain.com/lorem/ipsum/dolor", "")
But it's probably overkill here. #newfurniturey's answer of Substring with LastIndexOf is probably best.
I like to create a String Extension for stuff like this:
/// <summary>
/// Returns with suffix removed, if present
/// </summary>
public static string TrimIfEndsWith(
this string value,
string suffix)
{
return
value.EndsWith(suffix) ?
value.Substring(0, value.Length - suffix.Length) :
value;
}
You can then use like this:
var myString = "/lorem/ipsum/dolor";
myStringClean = myString.TrimIfEndsWith("/dolor");
You now have a re-usable extension across all of your projects that can be used to remove one trailing character or multiple.
using System.IO;
mystring.TrimEnd(Path.AltDirectorySeparatorChar); // To remove "/"
mystring.TrimEnd(Path.DirectorySeparatorChar); // To remove "\"
while (input.Last() == '/' || input.Last() == '\\')
{
input = input.Substring(0, input.Length - 1);
}
Thank you #Curt for your question.
I slightly improved #newfurniturey's code, and here is my version.
if(str.Contains('/')){
str = str.Substring(0, str.LastIndexOf('/'));
}
I'm way late to the party, but if you're using C# 8.0+, another clean approach would be to use the range operator:
if (urlStr.EndsWith("/")) urlStr = urlStr[..^1];
If you're curious as to how this works, take a look at the spec for ranges in C#:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/ranges
tldr; urlStr[..^1] roughly translates to something along the lines of "Give me a substring comprised of the characters contained within the range of index 0 to whatever index is 1 away from the last index.".
In other words, it's similar to...
urlStr.Substring(0, urlStr.Length-1)
Sometime I want to join two strings with a space in between. But if second string is null, I don't want the space.
Consider following code:
void AssertFoo(bool cond, string message = null) {
...
Assert.Fail("Something is foo.{0}", message != null ? " " + message : "");
...
}
Is there a more elegant way to do that?
Here is one option that I like. It's better if you already have an IEnumerable<string> with your data, but it's easy enough even if you don't. It also clearly scales well to n strings being joined, not just 1 or two.
string[] myStrings = new string[]{"Hello", "World", null};
string result = string.Join(" ", myStrings.Where(str => !string.IsNullOrEmpty(str)));
Here is another option. It's a bit shorter for this one case, but it's uglier, harder to read, and not as extensible, so I would probably avoid it personally:
//note space added before {0}
Assert.Fail("Something is foo. {0}", message ?? "\b");
In this case we add the space to the format string itself, but if message is null we instead use the backspace character to remove the space that we know is before it in the message.
For newer versions of C# you can use the following extension method:
public static string Prepend(this string value, string prepend) => prepend + value;
It can be used like this:
Assert.Fail("Something is foo.{0}", message?.Prepend(" "));
Added in 2020:
Today I use this:
public static string Surround(this object value, string prepend, string append = null) => prepend + value + append;
Try this:
string joinedString = string.IsNullOrEmpty(message2) ? message1 : message1 + " " + message2;
Assert.Fail("Something is foo.{0}", (" " + message).TrimEnd());
Sure, this will result in a few string object creations, but it's unlikely such micro-optimization issues would matter in the vast majority of programs. It might be considered an advantage of this method that it handles not just null message, but a message of all whitespace as well.
Assert.Fail("Something is foo.{0}", message?.PadLeft(message.Lenght + 1, ' '));
Since C#6 you can use string interpolation like this:
$"Something is foo. {mssg}".TrimEnd();
See it in .NET Fiddle
The most elegant way is to use the inbuilt keyword of String class.
String.IsNullOrEmpty
This way you wont have a problem.
I want to make sure that _content does not end with a NewLine character:
_content = sb.ToString().Trim(new char[] { Environment.NewLine });
but the above code doesn't work since Trim seems to not have an overloaded parameter for a collection of strings, only characters.
What is the simplest one-liner to remove an Enivronment.Newline from the end of a string?
The following works for me.
sb.ToString().TrimEnd( '\r', '\n' );
or
sb.ToString().TrimEnd( Environment.NewLine.ToCharArray());
.Trim() removes \r\n for me (using .NET 4.0).
How about:
public static string TrimNewLines(string text)
{
while (text.EndsWith(Environment.NewLine))
{
text = text.Substring(0, text.Length - Environment.NewLine.Length);
}
return text;
}
It's somewhat inefficient if there are multiple newlines, but it'll work.
Alternatively, if you don't mind it trimming (say) "\r\r\r\r" or "\n\n\n\n" rather than just "\r\n\r\n\r\n":
// No need to create a new array each time
private static readonly char[] NewLineChars = Environment.NewLine.ToCharArray();
public static string TrimNewLines(string text)
{
return text.TrimEnd(NewLineChars);
}
Use the Framework. The ReadLine() method has the following to say:
A line is defined as a sequence of
characters followed by a line feed
("\n"), a carriage return ("\r") or a
carriage return immediately followed
by a line feed ("\r\n"). The string
that is returned does not contain the
terminating carriage return or line
feed.
So the following will do the trick
_content = new StringReader(sb.ToString()).ReadLine();
What about
_content = sb.ToString().Trim(Environment.NewLine.ToCharArray());
_content = sb.TrimEnd(Environment.NewLine.ToCharArray());
This will of course remove "\r\r\r\r" as well as "\n\n\n\n" and other combinations.
And in "enviroments" where NewLine is other than "\n\r" you might get some strange behaviors :-)
But if you can live with this then I belive this is the most effectiv way to remove new line characters at the end of a string.
How about just:
string text = sb.ToString().TrimEnd(null)
That will pull all whitespace characters from the end of the string -- only a problem if you wanted to preserve non-newline whitespace.
Somewhat of a non-answer, but the easiest way to trim a newline off of a string is to not have the newline on the string in the first place, by making sure it is is never seen by your own code. That is, by using native functions which remove the newline. Many stream and file/io methods will not include the newline if you ask for output line by line, though it may be necessary to wrap something in a System.IO.BufferedStream.
Things like System.IO.File.ReadAllLines can be used in place of System.IO.File.ReadAllText most of the time, and ReadLine can be used instead of Read once you are working with the right type of stream (e.g. BufferedStream).
As Markus pointed out TrimEnd is doing the job now. I needed to get line feeds and white space from both ends of string in Windows Phone 7.8 environment. After having chased different more complex options my problem was solved by using Trim() only - passed the following tests nicely
[TestMethod]
[Description("TrimNewLines tests")]
public void Test_TrimNewLines()
{
Test_TrimNewLines_runTest("\n\r testi \n\r", "testi");
Test_TrimNewLines_runTest("\r testi \r", "testi");
Test_TrimNewLines_runTest("\n testi \n", "testi");
Test_TrimNewLines_runTest("\r\r\r\r\n\r testi \r\r\r\r \n\r", "testi");
Test_TrimNewLines_runTest("\n\r \n\n\n\n testi äål., \n\r", "testi äål.,");
Test_TrimNewLines_runTest("\n\n\n\n testi ja testi \n\r\n\n\n\n", "testi ja testi");
Test_TrimNewLines_runTest("", "");
Test_TrimNewLines_runTest("\n\r\n\n\r\n", "");
Test_TrimNewLines_runTest("\n\r \n\n \n\n", "");
}
private static void Test_TrimNewLines_runTest(string _before, string _expected)
{
string _response = _before.Trim();
Assert.IsTrue(_expected == _response, "string '" + _before + "' was translated to '" + _response + "' - should have been '" + _expected + "'");
}
I had to remove the new lines all over the text. So I used:
while (text.Contains(Environment.NewLine))
{
text = text.Substring(0, text.Length - Environment.NewLine.Length);
}