我有string col= "AB21"
一个excel细胞的位置.
我想将其解析为string column = "AB"
&int row = 21;
我怎样才能做到这一点?
Ser*_*kiy 10
string col = "AB21";
int startIndex = col.IndexOfAny("0123456789".ToCharArray());
string column = col.Substring(0, startIndex);
int row = Int32.Parse(col.Substring(startIndex));
Run Code Online (Sandbox Code Playgroud)
当然,您应该保证输入字符串的格式正确.
您有一个选项是使用正则表达式来验证和解析输入字符串.请参阅下面的代码.
using System;
using System.Text.RegularExpressions;
namespace DemoRegExForStackOverflow
{
class Program
{
static void Main(string[] args)
{
var regex = new Regex(@"(?<col>([A-Z]|[a-z])+)(?<row>(\d)+)");
var input = @"AB12";
var match = regex.Match(input);
if( match != null )
{
var col = match.Groups["col"];
var row = match.Groups["row"];
Console.WriteLine("Input is: {0}", input);
Console.WriteLine("Column is {0}", col.Value);
Console.WriteLine("Row is {0}", row.Value);
}
else
{
throw new ArgumentException("Invalid input");
}
}
}
}
Run Code Online (Sandbox Code Playgroud)