Home > Back-end >  I need to check if CHAR from Array1 contains some CHAR from my Array2 but I cant use Contains for CH
I need to check if CHAR from Array1 contains some CHAR from my Array2 but I cant use Contains for CH

Time:11-24

I need to convert one phone number (badly written) to correct format. Example: 420 741-854()642. to 420741854642 enter image description here

CodePudding user response:

I think I'd just Regex replace all non digits with nothing;

var messy = "  420 741-854()642";
var clean = Regex.Replace(messy, "[^ 0-9]", "");

For the regex pattern [^ 0-9] this means "a single character that is from, the set of: (all characters except) or 0 to 9 so in practice this pattern matches the space , hyphen -, parentheses () etc.. And any matched character (i.e. a bad character) is replaced with nothing

CodePudding user response:

This is a job for RegEx (Regular Expressions) :) you could have something like this: / ?\d /gm which will return three matches from 420741-854()642 as [' 420741', '854', '642'] which can of course then be concatenated. You could always as well replace the ' ' with '00' beforehand and just concatenate matches from /\d /gm. This just matches all digits in the string.

https://regex101.com/ is a great resource for learning RegEx.

CodePudding user response:

Technically, you can filter out digits (c >= '0' && c <= '9') with a help of Linq:

using System.Linq;

...

string source = "  420 741-854()642.";

string result = " "   string.Concat(source.Where(c => c >= '0' && c <= '9'));

CodePudding user response:

If you want to do it in the style you showed in the image then you can fix it by doing this:

        string number = "  420 741-854()642.";
        char[] povolene = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ' ' };

        for(int i = 0; i < number.Length; i  ) {
            if (povolene.Contains(number[i])) {

                .
                .
                .
            }
        }
  • Related