Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if string ends with special character c# [closed]

Tags:

c#

Hi I am looking for a solution with checks out if the string ends with a special character, If yes then remove it. The new string after removing special character should also not contain special character.

The special characters should be in array [!@#$%&/{()}=?+] to check against in end of string.

like image 259
Adnan Zameer Avatar asked Jan 20 '26 18:01

Adnan Zameer


1 Answers

How about using String.TrimEnd? This method is specifically for removing the characters in a given array from the string.

var newstr = s.TrimEnd("[!@#$%&/{()}=?+]".ToCharArray());

Also, the following requirement looks like you should be using String.Replace to replace any unwanted character in your string:

The new string after removing special character should also not contain special character

In that case you should do something like this:

string unwanted = "[!@#$%&/{()}=?+]";
for (int i = 0; i < unwanted.Length; i++)
    s = s.Replace(unwanted.Substring(i, 1), "");

Which removes all occurrances of all unwanted characters from the entire string.

like image 193
Thorsten Dittmar Avatar answered Jan 23 '26 06:01

Thorsten Dittmar