Trimming degree symbol on C#

1k views Asked by At

Can anyone tell me why this is not working:

string txt = "+0°1,0'";
string degree = txt.TrimEnd('°');

I am trying to separate the degrees on this string, but after this, what remains on degree is the same content of txt.

I am using C# in Visual Studio.

3

There are 3 answers

4
vernou On BEST ANSWER

string.TrimEnd remove char at the end. In your example, '°' isn't at the end.

For example :

string txt = "+0°°°°";
string degree = txt.TrimEnd('°');
// degree => "+0"

If you want remove '°' and all next characters, you can :

string txt = "+0°1,0'";
string degree = txt.Remove(txt.IndexOf('°'));
// degree => "+0"
2
Biju Kalanjoor On
string txt = "+0°1,0'";
if(txt.IndexOf('°') > 0) // Checking if character '°' exist in the string
{
   string withoutdegree = txt.Remove(txt.IndexOf('°'),1);
}
0
Sai Gummaluri On

Another safe way of handling the same is using the String.Split method. You will not have to bother to verify the presence of the character in this case.

string txt = "+0°1,0'";
var str = txt.Split('°')[0]; // "+0"
string txt = "+01,0'";
var str = txt.Split('°')[0]; // "+01,0'"

You can use this to remove all the '°' symbols present in your string using String.Replace

string txt = "+0°1,0'°°";
var text = txt.Replace(@"°", ""); // +01,0'

Edit: Added a safe way to handle the OP's exact query.