Can't clear the white spaces with the most common methods - c#
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();
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;
Split string to array when some elements are empty
I need to process a large amount of csv data in real time as it is spat out by a TCP port. Here is an example as displayed by Putty: MSG,3,1920,742,4009C5,14205994,2017/01/29,20:14:27.065,2017/01/29,20:14:27.972,,8000,,,51.26582,-0.33783,,,0,0,0,0 MSG,4,1920,742,4009C5,14205994,2017/01/29,20:14:27.065,2017/01/29,20:14:27.972,,,212.9,242.0,,,0,,,,, MSG,1,1920,742,4009C5,14205994,2017/01/29,20:14:27.065,2017/01/29,20:14:27.972,BAW469,,,,,,,,,,, MSG,3,1920,742,4009C5,14205994,2017/01/29,20:14:27.284,2017/01/29,20:14:27.972,,8000,,,51.26559,-0.33835,,,0,0,0,0 MSG,4,1920,742,4009C5,14205994,2017/01/29,20:14:27.284,2017/01/29,20:14:27.972,,,212.9,242.0,,,0,,,,, I need to put each line of data in string (line) into an array (linedata[]) so that I can read and process certain elements, but linedata = line.Split(','); seems to ignore the many empty elements, with the result that linedata[20], for example, may or may not exist, and if it doesn't I get an error if I try to read it. Even if element 20 in the line contains a value it won't necessarily be the 20th element in the array. And that's no good. I can work out how to parse line character by character into linedata[], inserting an empty string where appropriate, but surely there must be a better way ? Have I missed something obvious ? Many Thanks. Perhaps I'd better add that I'm quite new to C#, my past experience is all with Delphi 7. I really miss stringlists. Edited: sorry, this is now resolved with the help of MSDN's documentation. This code works: lineData = line.Split(separators, StringSplitOptions.None); after setting "string[] separators = { "," };". My big mistake was to follow examples found on tutorial sites which didn't give any clues that the .split method had any options.
https://msdn.microsoft.com/en-us/library/system.stringsplitoptions(v=vs.110).aspx That link has an example section, look at example 1b specifically. There is an extra parameter to Split called StringSplitOptions which does this. For Example: string[] linedata = line.Split(charSeparators, StringSplitOptions.None); foreach (string line in linedata) { Console.Write("<{0}>", line); } Console.Write("\n\n"); The way to find this sort of information is to start with the Reference Documentation for the function, and hope it has an option or a link to a similar function. If you want to also start validating types, handling variants in the format etc... you could move up to a CSV library. If you do not need that functionality, this is the easiest way and efficient for small files.
Some of the overloads for String.Split() take a StringSplitOptions argument, and if you use the RemoveEmptyEntries option, it will...remove the empty entries. So you can specify the None option: linedata = line.Split(new [] { ',' }, StringSplitOptions.None); Or better yet, use the overload that doesn't take a StringSplitOptions, which treats it as None by default: linedata = line.Split(','); The code in your question indicates that you are doing this, but your description of the problem suggests that you are not. However, you're probably better off using an actual CSV parser, which would handle things like unescaping and so on.
The StringReader class provides methods for reading lines, characters, or blocks of characters from a string. Hope this could be the clue string str = #"MSG,3,1920,742,4009C5,14205994,2017/01/29,20:14:27.065,2017/01/29,20:14:27.972,,8000,,,51.26582,-0.33783,,,0,0,0,0 MSG,4,1920,742,4009C5,14205994,2017/01/29,20:14:27.065,2017/01/29,20:14:27.972,,,212.9,242.0,,,0,,,,, MSG,1,1920,742,4009C5,14205994,2017/01/29,20:14:27.065,2017/01/29,20:14:27.972,BAW469,,,,,,,,,,, MSG,3,1920,742,4009C5,14205994,2017/01/29,20:14:27.284,2017/01/29,20:14:27.972,,8000,,,51.26559,-0.33835,,,0,0,0,0 MSG,4,1920,742,4009C5,14205994,2017/01/29,20:14:27.284,2017/01/29,20:14:27.972,,,212.9,242.0,,,0,,,,,"; using (StringReader reader = new StringReader(str)) do { string[] linedata = reader.ReadLine().Split(','); } while (reader.Read() != -1);
While you should look into the various ways the String class can help you here, sometimes the quick and dirty "MAKE it fit" option is called for. In this case, that'd be to roll through the strings in advance and ensure you have at least one character between the commas. public static string FixIt(string s) { return s.Replace(",,", ", ,"); } You should be able to: var lineData = FixIt(line).Split(','); Edit: In response to the question below, I'm not sure what you meant, but if you mean doing it without creating a helper method, you can do so easily. The code will be harder to read and troubleshoot if you do it in one line though. My personal rule is, if you have to do it a LOT, it should probably be a method. If you only had to do it once, this is particularly clean. I'd actually do it this way and just wrap it in a method that does all the work for you. var lineData = line.Replace(",,", ", ,").Split(','); As a method, it'd be: public static string[] GiveMeAnArray(string s) { return s.Replace(",,", ", ,").Split(','); }
Replacing strings with changing data
I've been looking at encryption and long story short, I need to remove an xml tag from a string. Each string needs a global rule for replacing the string, and I've looked at regex for this, but it doesn't make sense. Here are some examples <BitStrength>384</BitStrength> <BitStrength>1024</BitStrength> <BitStrength>12300</BitStrength> I need to replace the whole string and the number inside as well, with nothing. I've tried things like: string.replace("<BitStrength>12300</BitStrength>",""); But the issue is the length and characters of the number, and a match is never found. Has anyone got a solution? Maybe regex is the way to go? PS. Preferably a solution in C#. EDIT: I'm looking for a solution that replaces the whole string in not only this kind of example but strings in general. <BitStrength>4633</BitStrength> <BitStrength>336</BitStrength> !!SomeConstantData!!5437!!EndConstant!! I would like 2 eggs today. I would like 17 eggs today. I would like 258367 eggs today. Now if I put string.replace("I would like ","").replace(" eggs today.") I would be left with the number 258367, because I didn't cover this in my statement. I'm looking for a solution to delete this data. It can be any value. In my particular example I'm looking to replace <BitStrength>384</BitStrength> in <BitStrength>384</BitStrength><RSAKeyValue><Modulus>code</Modulus><Exponent>code</Exponent></RSAKeyValue> The Issue I face is that the number between the bitstrength tags can be anything between 386 and 16384, and I need to remove the entire bitstrength string.
string input = "<BitStrength>384</BitStrength>"; string pattern = #"<BitStrength>\d*</BitStrength>"; string replacement = " "; Regex rgx = new Regex(pattern); string result = rgx.Replace(input, replacement); Console.WriteLine("Original String: {0}", input); Console.WriteLine("Replacement String: {0}", result); returns Original String: <BitStrength>384</BitStrength> Replacement String:
You don't show what you have tried, and I wonder if the failure is because you are not making the pattern string as a literal using the # before it? This example works: Regex.Replace(#"Blah<BitStrength>12300</BitStrength>Blah", #"(\<BitStrength\>12300\</BitStrength\>)", string.Empty) and returns BlahBlah If the actual number does not matter use this pattern: (\<BitStrength\>\d+\</BitStrength\>)
This works: var source = string.Join(Environment.NewLine, "<BitStrength>384</BitStrength>", "<BitStrength>1024</BitStrength>", "<BitStrength>12300</BitStrength>"); var result = source.Replace("<BitStrength>12300</BitStrength>", string.Empty);
about string removing in 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.