c# - 如何从字符串中分离字符和数字部分

标签 c# string

例如,我想分开:

  • OS234OS234
  • AA4230AA4230

我使用了以下简单的解决方案,但我很确定应该有一个更有效和更强大的解决方案。

private void demo()
    {   string cell="ABCD4321";
        int a = getIndexofNumber(cell);
        string Numberpart = cell.Substring(a, cell.Length - a);
        row = Convert.ToInt32(rowpart);
        string Stringpart = cell.Substring(0, a);
    }

private int getIndexofNumber(string cell)
        {
            int a = -1, indexofNum = 10000;
            a = cell.IndexOf("0"); if (a > -1) { if (indexofNum > a) { indexofNum = a; } }
            a = cell.IndexOf("1"); if (a > -1) { if (indexofNum > a) { indexofNum = a; } }
            a = cell.IndexOf("2"); if (a > -1) { if (indexofNum > a) { indexofNum = a; } }
            a = cell.IndexOf("3"); if (a > -1) { if (indexofNum > a) { indexofNum = a; } }
            a = cell.IndexOf("4"); if (a > -1) { if (indexofNum > a) { indexofNum = a; } }
            a = cell.IndexOf("5"); if (a > -1) { if (indexofNum > a) { indexofNum = a; } }
            a = cell.IndexOf("6"); if (a > -1) { if (indexofNum > a) { indexofNum = a; } }
            a = cell.IndexOf("7"); if (a > -1) { if (indexofNum > a) { indexofNum = a; } }
            a = cell.IndexOf("8"); if (a > -1) { if (indexofNum > a) { indexofNum = a; } }
            a = cell.IndexOf("9"); if (a > -1) { if (indexofNum > a) { indexofNum = a; } }

            if (indexofNum != 10000)
            { return indexofNum; }
            else
            { return 0; }


        }

最佳答案

正则表达式最适合这种工作:

using System.Text.RegularExpressions;

Regex re = new Regex(@"([a-zA-Z]+)(\d+)");
Match result = re.Match(input);

string alphaPart = result.Groups[1].Value;
string numberPart = result.Groups[2].Value;

关于c# - 如何从字符串中分离字符和数字部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1968049/

相关文章:

c# - 如何从 C# 中的响应中提取和获取值

sql - mysql自己连接表

ruby - 为什么 .to_s 会破坏这段代码?

string - Haskell 函数

c# - 如何从 angularjs 正确地将视频文件上传到 Azure 媒体服务

c# - 如何通过 Entity 框架自动为 Oracle 数据库生成标识?

c# 类引用而不是实例引用

c# - 使用 Stripe 的 Payment Intent API 接受 Xamarin 表单中的付款

ruby-on-rails - 如何将这两个 Ruby 字符串测试结合到一个正则表达式中?

c - 什么解释了 C 编译器 w.r.t 字符串初始化的这种行为?