Trimming a string, removing the last character in C #

I'm having trouble removing the backslash from my string. The line is similar to "3adsadas34 \". I want to remove the backslash at the end, I tried:

urlContent = realUrl.Remove(realUrl.Length - 1, 1); 

But he does not want to work. I would like to know if I can use a regex, and if possible maybe someone can provide a regex pattern to remove the '\' from this line or some other way to remove the backslash is more than welcome. Thanks in advance, Laziale

+4
source share
8 answers

try it

 urlContent = realUrl.TrimEnd('\\'); 

Note. You should avoid backslashes.

 char ch = '\\'; string s = "\\"; string verbatimString = @"\"; 

The Remove code looks fine. realUrl.Substring(0, realUrl.Length-1) will do the same. The problem could be somewhere else.

+11
source
 urlContent = realUrl.TrimEnd('\\'); 

Keep in mind that you must avoid the backslash with another backslash in order for this to work.

+2
source

For example, a very naive implementation:

 public static string RemoveTrailingBackslash(string text) { if (text.EndsWith("\\") && text.Length > 1) return text.Substring(0, text.Length - 1); return text; } 
+1
source

Do this: -

 Regex.Replace(str, @"\\$", ""); 
+1
source

To remove all backslashes at the end, call string.TrimEnd('\\') , as other posters wrote.

To remove only the latter (assuming there are a few backslashes at the end), do something like:

 if ( realUrl!=null && realUrl.EndsWith('\\') ) { urlContent = realUrl.Substring(0, realUrl.Length-1 ); } else { urlContent = realUrl; } 
+1
source

you can use the end of cropping,

 realUrl.TrimEnd('\\'); 

Remember that this will delete all return inputs '\'

0
source
 urlContent = realUrl.Substring(0, realUrl.Length - 1); 

should also work

0
source
  string realUrl="3adsadas34\\"; string urlContent = realUrl.Remove(realUrl.Length - 1, 1); 
0
source

Source: https://habr.com/ru/post/1400451/


All Articles