Remove characters in string in C# - 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;

Related

Wrong result when Split a string when the given characters are not found

When I tried to split a string value of some text here with ++. I expected the result to be an empty list. Since the ++ is not found in the string some text here, the result of a Count on the List should be 0.
However, the result I get is 1 (when I Count on the List).
How am I able to determine if the string has no ++ in it ? (a Count did not work)
List<string> l = value.Split("++").ToList();
The observed behavior is by design. If delimiter is not found a collection with a single item is returned. As documentation states:
If this instance does not contain any of the characters in separator, the returned array consists of a single element that contains this instance.
If you want to check if delimiter exists you can use .Contains("++") or .IndexOf("++") != -1
By default, if no matches are found it returns the string in a array of size one.
How am I able to determine if the string has no ++ in it ?
if (value.Contains("++"))
edit: wow a bunch of answers already while i was writing this. :D
As #Gilad and others have pointed out, this is indeed the expected output. If a string does not contain the split value, the entire string is returned as the first item in the list.
If you plan on using this split value later, you can still use the .Split() method to determine if your split string is contained within the string, by simply checking if the count is equal to 1:
List<string> l = value.Split(new[] {"++"}).ToList();
if (l.Count == 1) {
//++ was not found in the string
} else {
//++ was found in the string (l.Count-1) times
}
Note of caution: It's less efficient to split a string, and allocate an array, than simply just checking with a method such as .Contains(). Use the above solution, if you may actually use the above split items later in the code.
If there is no "++" in the string, you get back the original string. If there are n "++"'s in the string, you get n+1 splits returned. You code is fine except that it needs an array passed:
var l = value.Split(new string[] {"++"}, StringSplitOptions.None).ToList();
So when l.Count() == 1 then there is no "++" in the string

c# "Cannot convert from 'string[]' to 'string'

I'm trying to make a list in string to get the usernames like this:
string[] whitelisted = { "example", "exampøle222", "example245"};
if (sentRequest.Sender.Username.ToLower().Contains(whitelisted))
You are checking if the username contains the list. You should be checking that the list contains the username.
whitelisted.Contains(sentRequest.Sender.Username.ToLower())
Your comparison is backwards. You need to see whether the array contains the string .
You probably want to check that the sentRequest.Sender.Username.ToLower() is present in the whitelisted list, right?
Then make it inverted if (whitelisted.Contains(sentRequest.Sender.Username.ToLower()))
The error you get says that the method you are calling i.e. string.Contains() can accept a string but cannot accept an array string[].
It can be done quite simply using the LINQ aggregate function.
string[] strings = {"example1","example2"};
string result = strings.Aggrigate((l,r)=>l+r);
You could also use the String.Join method
string[] strings = {"example1","example2"};
string result = String.Join("",strings);
However when I look at the rest of your code I would recommend solving the problem something like this.
if(whitelisted.IndexOf(sentRequest.Sender.Username.ToLower()) != -1)
That if statement will only be executed if the Username is in the white list.

Combine string[] to string

Is there a quick way to pack an array of strings to a string?
More specifically,I have an array of strings like this:
string[] Operators = {"+","-","x","/"} and I would like to pack it to
string sOperators = "+-x/"
Of course, the obvious way is to read each item in the array and put it in the string individually, but is there a better way that people smarter than me can think of?
I have tried:
string sOperators="";
String.Join(sOperators,Operators);
Unfortunately, that won't work for me. Any thought?
Your code sample could just be incomplete but based on you've posted the problem is that you're not assigning the joined string anywhere. I think the following will do what you want;
string joined = String.Join(sOperators, Operators);
Join returns a new string, it does not make any changes to the arguments you pass it. You need to assign the return value to some field, property, constant, or variable in order to produce the desired result.
You can use String.Concat(Operators) (MSDN http://msdn.microsoft.com/en-us/library/k9c94ey1.aspx)
You can indeed use String.Join for this:
string sOperators = string.Join("", Operators);
I guess you just forgot to assign the result to a variable.

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();

Simple way to trim Dollar Sign if present in C#

I have a DataRow and I am getting one of the elements which is a Amount with a dollar sign. I am calling a toString on it. Is there another method I can call on it to remove the dollar sign if present.
So something like:
dr.ToString.Substring(1, dr.ToString.Length);
But more conditionally in case the dollar sign ever made an appearance again.
I am trying to do this with explicitly defining another string.
Convert.ToString(dr(columnName)).Replace("$", String.Empty)
--
If you are working with a data table, then you have to unbox the value (by default its Object) to a string, so you are already creating a string, and then another with the replacement. There is really no other way to get around it, but you will only see performance differences when dealing with tens of thousands of operations.
You could also use
string trimmed = (dr as string).Trim('$');
or
string trimmed = (dr as string).TrimStart('$');
If you are using C# 3.0 or greater you could use extension methods.
public static string RemoveNonNumeric(this string s)
{
return s.Replace("$", "");
}
Then your code could be changed to:
((String)dr[columnName]).RemoveNonNumeric();
This would allow you to change the implementation of RemoveNonNumeric later to remove things like commas or $ signs in foreign currency's, etc.
Also, if the object coming out of the database is indeed a string you should not call ToString() since the object is already a string. You can instead cast it.
Regex would work.
Regex.Replace(theString, "$", "");
But there are multiple ways to solve this problem.
dr[columeName].ToString().Replace("$", String.Empty)
Why don't you update the database query so that it doesn't return the dollar sign? This way you don't have to futz with it in your C# code.

Categories

Resources