I want one character to exit IsLetterOrDigit

I have the following function that checks a string and stores only letters and numbers. All other characters are deleted.

However, I want one character only "-" to exit this function and not be deleted. For example, I want Jean-Paul to remain with a “-” between the two names. How can i do this?

String NameTextboxString = NameTextbox.Text;
NameTextboxString = new string((from c in NameTextboxString
                                where char.IsLetterOrDigit(c) 
                                select c).ToArray);
nameLabel.Text = NameTextboxString;
+4
source share
3 answers

You may try:

where char.IsLetterOrDigit(c) || c == '-'

Assuming the user will not enter a string like --lolol-i-am-an-hackerz--


To simplify the code a bit:

nameLabel.Text = new string(NameTextbox.Text.Where((c => char.IsLetterOrDigit(c) || c == '-')).ToArray());
+10
source

A small extension method may also come in handy:

public static class CharExtensions
{
    public static bool IsLetterDigitOrSpecialChar(this char c, 
              params char[] specialCharacters)
    {
        return char.IsLetterOrDigit(c) || specialCharacters.Any(x => c.Equals(x));
    }
}

And then use it like this:

NameTextboxString = new string(
        NameTextboxString.Where(x => x.IsLetterDigitOrSpecialChar(('-'))).ToArray());
+3
source

where:

from c in name where char.IsLetterOrDigit(c) || c=='-' select c

. :

using System;
using System.Linq;

public class Program
{
    public static void Main()
    {
        var name = ""Jean-Paul@@~()"";
        var cleaned_name= new string((from c in name where char.IsLetterOrDigit(c) || c=='-' select c).ToArray());
        Console.WriteLine(cleaned_name);
    }
}

:

Jean-Paul
0

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


All Articles