about string removing in C# - c#

Whats is correct to do?
check if exists, then remove?
var input = "foo #main baa";
if(input.Contains("#main")) {
input = input.Replace("#main", "");
}
or just:
input = input.Replace("#main", "");
Well, this seem a simple question,but I really want know.
Thanks in advance.

The Contains check actually just makes your code slower.
Remove it.
The Contains call needs to loop through the string until it finds #main.
The Replace call then needs to do the same exact loop (it can't remember it from the Contains call).
This is a Shlemiel the Painter's algorithm.
Replace can handle strings with zero or more occurrences of the search string, so you don't need the check.

Just do the replacement - if it's not there, nothing should happen.

Just make the call to Replace(). If the substring isn't found nothing happens and you avoid an additional call to Contains().

I would do this:
input = input.Replace("#main", "").Replace(" "," ");
To remove any double spaces.

Just remove it. The only thing to check is if the string is null or not.

Related

Remove some text from a filename on save

Ok what I am doing is selecting a file name and saving the filename only. What I need to do is remove certain text from it but it changes and that's the issue I am having.
The main one is it has name_zm and I want to remove _zm from the name.
But some other files have ak47_fmg_mp and all i want is the first before the _
but not sure how to accomplish this.
I have tried text replace regex even but none of it has worked
string result = nyu_res.filename;
result = result.Replace("_zm", "");
Well when i select a file it saves the filename in this example. Lets say I selected
m14_zm
What I want to do is get m14 and thats it. Same with the others. Just want to get to the first '_'. I tried the code above but could not get it to work.
Any help would be much appreciated.
Use Split('_') and take the first one.
Then you don't have to check if it contains _ or not.
result = result.Split('_')[0];
Check your string for Null/Empty and '_' then you can use Substring and IndexOf to do that :
var result = "fileName_zm";
if(!string.IsNullOrEmpty(result) && result.Contains('_'))
{
result = result.Substring(0, result.IndexOf("_"));
}
Advantage: if string is Null/Empty it will short circuit and you will save few cycles of CPU.

Remove characters in string in C#

I have the following field that is calling the database Phone_Number. I would like to remove the 1- when the number is displayed.
So instead of displaying 1-###-###-####, I would like to display ###-###-####.
I tried the following:
string x= Phone_Number;
x.Remove(0,1);
Response.Write(x);
However, it keeps displaying 1-###-###-####.
What am I doing wrong?
Strings are immutable in C# - String.Remove call does not modify original string. It creates the new string in which specified characters are deleted and returns it. You should display result of this method call instead:
Response.Write(x.Remove(0,2)); // you should remove 2 characters
Or
Response.Write(x.Substring(2));
You need to set the result to x. strings are immutable in C#:
x = x.Remove(0,1)
Another method would be:
if (x.StartsWith("1-")
x = x.Remove(0,2);
This has the benefit of doing nothing if you get a phone number without the leading 1-.
Thanks to commenter for pointing out my error.
As you see there are too many ways to remove substrings from strings. A new way that you can also use is a Regular Expression just in case the value you want to remove have a complex pattern in the future.
var x = phoneNumber;
var result = Regex.Match(x, #"^(1-)?(.*)$").Groups[2].Value;

Can't clear the white spaces with the most common methods

This is the case - I need to work with the Text property of a ToolStripItem and I need to clear all white spaces from the string before that. However I tried three very common (in my opinion) scenarios and neither of them returned a string with no white spaces. Here is what I tried:
string tempBtnText = tempItem.Text;
tempBtnText is defined inside the method where I work with the Text property. I find it easier this way. Then I tried those:
tempBtnText.Replace(" ", String.Empty);
tempBtnText = Regex.Replace(tempItem.Text, #"^\s*$\n", string.Empty);
string tempBtnTexts = Regex.Replace(tempItem.Text, #"\s+", "");
All those returned the string in it's original form (with white spaces). The only way to remove the white spaces was by using this method :
public string RemoveWhitespace(string input)
{
return new string(input.ToCharArray()
.Where(c => !Char.IsWhiteSpace(c))
.ToArray());
}
Which I found in a similar post here in SO. but I really don't understand why all of the above approaches don't work. I'm starting to think that there is something to do with the fact that I'm using a ToolStripItem Text property but as shown at the very begining I declare my own string variable that takes the value of the Text property and.
I don't know. Can someone tell me, what is the reason of this behavior. Not that it's that big of a problem to use another method for clearing the white spaces but the not working options are much more compact and readable and I would like to use one of them if possible.
Strings are immutable, what means that any operation produces a new instance, so you need assign any method result back to input:
string input = "...";
intput = intput.Replace(x, y);
You are not assigning the result back to tempBtnText
tempBtnText.Replace(" ", String.Empty);
it should be:
tempBtnText = tempBtnText.Replace(" ", String.Empty);
strings are immutable, string.Replace returns a new string, it doesn't modify the existing one.
abatischev is right so writing
tempBtnText = tempBtnText.Replace(" ", String.Empty);
should solve your problems. If you only want to remove Whitespaces in front and back then rather use:
tempBtnText = tempBtnText.Trim();

How do I do multiple replaces on a string at the same time?

string rawConnString = Properties.Settings.Default.ConnectionString;
I want to do this with "rawConnString":
rawConnString.Replace("<<DATA_SOURCE>>", server);
rawConnString.Replace("<<INITIAL_CATALOG>>", "tempdb");
Then set the final string to variable finalConnString.
How would I go about doing this?
This is ASP .NET 4.0/C# btw.
string finalString = Properties.Settings.Default.ConnectionString.Replace("<<DATA_SOURCE>>", server).Replace("<<INITIAL_CATALOG>>", "tempdb");
will do it all in one line of code. But it's uglier IMO because you'll have to scroll. The code in your question seems a LOT cleaner and more readable to me.
And doing it in one line of code won't help your performance at all. It should all compile down to the same MSIL either way. I'd leave it as you had it.
Not sure if this is what you're after, but you can chain them:
var finalConnString = rawConnString.Replace("<<DATA_SOURCE>>", server)
.Replace("<<INITIAL_CATALOG>>", "tempdb");
If you're looking to do it with a single method call, I don't think there's anything native to .NET. You can always create an extension method though. Here's a performance-conscious ReplaceMany implementation (signature .ReplaceMany(string[] oldValues, string[] newValues)).
This is frankly trivial; you have 90% of the code you need:
string rawConnString = Properties.Settings.Default.ConnectionString;
string finalConnString = rawConnString
.Replace("<<DATA_SOURCE>>", server)
.Replace("<<INITIAL_CATALOG>>", "tempdb");
To avoid using two back-to-back calls of Replace, you can use regular expressions. However, this is far less readable than the original:
string connString = Regex.Replace(
rawConnString
, "(<<DATA_SOURCE>>)|(<<INITIAL_CATALOG>>)"
, m => m.Groups[1].Success ? server : "tempdb"
);
Link to ideone.
you mean something like this
string tempString=rawConnString.Replace("<<DATA_SOURCE>>", server);
sting finalstring=tempString.Replace("<<INITIAL_CATALOG>>", "tempdb");
First, String.replace does not change the original string: it creates a new string. So you have to assign the return value to something. So the logically simplest thing to do is:
finalstring=rawConnString.Replace("<<DATA_SOURCE>>", server);
finalstring=finalstring.Replace("<<INITIAL_CATALOG>>", "tempdb");
Note that for the second replace, you want to start with the results of the first replace, not the original string.
As String.replace returns a string, and String.replace takes a string, you might find it easier to run them together:
finalstring=rawConnString.Replace("<<DATA_SOURCE>>", server).Replace("<<INITIAL_CATALOG>>", "tempdb");

How to remove a part of the string

I am wondering How i can remove a part if my string .
For example my string will be :
string test = "/blabla/test/ok";
How can I say that I want to remove /blabla/ ?
And my string will be /test/ok.
test = test.Replace("/blabla/", string.Empty);
Or
test = test.Substring("/blabla/".Length - 1);
You really should take a look at the documentation of the String class and all the different methods and properties it holds.
How about stripping the first 8 characters?
test = test.Substring(7);
test = test.Replace("/blabla", "");
You could simply .Replace() it:
test.Replace("/blabla/",""); //Yields /test/ok
If you what to do it in more general case you'll need regular expressions here:
Regex.Replace(#"/blabla/test/ok", #"^//(.*?)//(.*?)//(.*?)$", #"/$2/$3")
It depends on whether you're going to be snipping out the same bit of text every single time or whether the text you're removing can differ.
If you know it's a particular block of text which will only appear once in the string then use Curt's answer (test = test.replace("/blabla", "");).
If it's anything else then, personally, I'd use a variant of Arcturus's answer to snip out the unwanted segment of the string (test = test.Substring(7);).
That's my two cents anyway.

Categories

Resources