Convert string from lowercase to uppercase and removing special charaters from a string using C#
I am developing a login form with User ID. I want the user to create the userid in a specified format. I need a method using C# to convert all lowercase letters to uppercase. The userid will be in the following fomat. The format is:
xyz\t4z4567 (characters are not case sensitive)
Rules:
1.Only special character \ is allowed while creating user name. 2.The UserID sholud be converted to uppercase.like (xyz --> XYZ) I need to check if user enters any special characters while creating the userid. If any special charcters are there in UserID the method needshold remove the special characters and should convert all lowercase to uppercase lettrs.
finally the result should be in the following way :
xyz\t4z45@67 ---> XYZ\T4Z4567
I used the following method to check whether the string contains the following characters and if so i am replacing with empty.
public string RemoveSpecialChars(string str)
{
string[] chars = new string[] { ",", ".", "/", "!", "@", "#", "$", "%", "^", "&", "*", "'", ";", "-", "_", 开发者_StackOverflow"(", ")", ":", "|", "[", "]" };
for (int i = 0; i < chars.Length; i++)
{
if (str.Contains(chars[i]))
{
str = str.Replace(chars[i], "");
}
}
return str;
}
Use the following Regex replacement:
outputStr = System.Text.RegularExpressions.Regex.Replace(inputStr, @"[^a-zA-Z0-9_\\]", "").ToUpperInvariant();
Input: inputStr=@"xya\t4z567"
output: "XYA\T4Z567"
Use "yourstring".ToUpper() and you can use "yourstring".Replace() to remove the special characters.
if ((c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '\')Firstly, string.ToUpper() gets your upper case characters.
To get rid of all special characters you would either use a regex or loop through the string and copy 'A-Z' and '/' in to a new string. This filters out all other characters without needing to know what they are.
E.g.
string invalid = @"as@bc3423*%*%ihh";
string upper = invalid.ToUpper();
string result = string.Empty;
foreach (char c in upper)
{
if ((c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '\\')
result += c;
}
Console.WriteLine(result);
精彩评论