String parsing, extracting numbers and letters

后端 未结 6 2100
逝去的感伤
逝去的感伤 2020-12-30 15:19

What\'s the easiest way to parse a string and extract a number and a letter? I have string that can be in the following format (number|letter or letter|number), i.e \"10A\",

6条回答
  •  Happy的楠姐
    2020-12-30 15:46

    The easiest and fastest is to use simple string operations. Use the IsDigit method to check where the letter is, and parse the rest of the string to a number:

    char letter = str[0];
    int index = 1;
    if (Char.IsDigit(letter)) {
       letter = str[str.Length - 1];
       index = 0;
    }
    int number = int.Parse(str.Substring(index, str.Length - 1));
    

提交回复
热议问题