1

I have to eliminate all special characters, alphabets and keep only the numbers in the string and store it into an integer. For example "$67%!" or "$127a%". I am obtaining data from serial port and in certain cases there are alphabets/ special chars between $ and % or may be a number after %. Currently, I have this snippet with me

string UartInput = serialcom.ReadLine();
int[] ints = UartInput.Trim(new[] { '$', '%' }).Split(' ').Select(int.Parse).ToArray();

I made a few needed changes and transmitted a single value at a time. The snippet was changed to

int ints = Convert.ToInt16(serialcom.ReadLine().Trim(new[] { '$', '%' }))

It was insufficient

ScottSummers
  • 310
  • 1
  • 13
  • 1
    Probably this is the best use case for a regex expression – Steve Feb 02 '17 at 09:04
  • If you want just the numbers from the string then there are threads on this already: http://stackoverflow.com/questions/2634731/best-way-to-get-all-digits-from-a-string – Equalsk Feb 02 '17 at 09:05
  • Maybe I'm not orthodox, why not minimal loop? Full debugging capabilities etc .... – Jacek Cz Feb 02 '17 at 09:09
  • 2
    Possible duplicate of [Best way to get all digits from a string](http://stackoverflow.com/questions/2634731/best-way-to-get-all-digits-from-a-string) – MakePeaceGreatAgain Feb 02 '17 at 09:09

3 Answers3

2

This might do the trick for you

string serialcomnum = Regex.Match(serialcom,"\\d+").ToString();
int ints = Convert.ToInt32(serialcomnum);

Another way could be

string serialcom = "$67%!$127a%";
var serialcomnum = Regex.Replace(serialcom, @"[^0-9]+", ",");
serialcomnum = serialcomnum.TrimStart(',').TrimEnd(',');
int[] serialints = serialcomnum.Split(',').Select(int.Parse).ToArray();
Mohit S
  • 13,723
  • 6
  • 34
  • 69
1

Probably a simple Regex is the easiest solution without using other string parsing methods

string input = "$67%!$127a%";
var matches = Regex.Matches(input, @"[0-9]+", RegexOptions.Compiled);
var result = matches.Cast<Match>()
                    .Select(x => Int32.Parse(x.Value)).ToArray();

foreach (int x in result)
    Console.WriteLine(x);

Here the example expects more than one number inside your input string and returns an array of integers. If this is not the case (only one integer expected) then you can replace the ToArray with a SingleOrDefault() and assign the result to an integer variable.

Also, if you have numbers bigger than Int32.MaxValue, then you should change the Int32.Parse with Int64.Parse.

Ghasan غسان
  • 5,577
  • 4
  • 33
  • 44
Steve
  • 213,761
  • 22
  • 232
  • 286
0

Haven't tested this, but i think it might work

int result = Int32.Parse(string.Concat(yourStringVarible.ToCharArray().TakeWhile(char.IsNumber)));

EDIT:

For getting the ints enclosed by other chars (not tested aswell):

public List<int> GetInts(string text){
 char[] chars = text.ToCharArray()
 bool prevIsNum = false;
 int startI = 0;
 int lenI = 0;
 List<int> ints = new List<int>();
 for(i=0;i<chars.length;i++){
    if(Char.IsNumber(chars[i])){
        if(prevIsNum){
            lenI ++;
        }else{
            startI = i;
            lenI ++;
        }
        prevIsNum = true;
    }else if(prevIsNum){
        prevIsNum = false;
        ints.add(Int32.Parse(string.Concat(chars.SubArray(startI,lenI)));
    }
 }
 return ints;
}
FS'Wæhre
  • 196
  • 2
  • 16
  • This will work if the user is expecting one integer per string, however, if it can contain multiple, then it won' work. – Ghasan غسان Feb 02 '17 at 09:41
  • `Where` instead of `TakeWhile` should fix it. Also, `ToCharArray` is not required, Where (and TakeWhile as well) require an `IEnumerable`, and string is `IEnumerable`. You will need a check for a string containing no digits, since `Int32.Parse`will throw on empty string – Gian Paolo Feb 02 '17 at 10:45