我有string col= "AB21"
这是一个excel小区位置。
我想将其解析为string column = "AB"
& int row = 21;
我该怎么做?
答案 0 :(得分:10)
string col = "AB21";
int startIndex = col.IndexOfAny("0123456789".ToCharArray());
string column = col.Substring(0, startIndex);
int row = Int32.Parse(col.Substring(startIndex));
当然,您应该保证输入字符串的格式正确。
答案 1 :(得分:5)
您有一个选项是使用正则表达式来验证和解析输入字符串。 请参阅下面的代码。
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");
}
}
}
}
答案 2 :(得分:1)
如果这是Excel,我会依赖Excel,因为有效范围的定义取决于版本。与之前的答案不同,此例程将拒绝看起来像范围但不是有效范围的字符串,例如Excel 2003,“XB21”或“AB66000”。我假设下面的函数可以转换为C#。
Sub SplitRangeStg(ByVal RngStg As String, ByRef RowNum As Long, _
ByRef ColNum As Long)
Dim RngErr As Boolean
Err.Number = 0
RngErr = False
On Error Resume Next
RowNum = Range(RngStg).Row ' Sets Err.Number if range invalid
If Err.Number <> 0 Then
RngErr = True
Err.Number = 0
End If
ColNum = Range(RngStg).Column ' Sets Err.Number if range invalid
If Err.Number <> 0 Then
RngErr = True
Err.Number = 0
End If
If RngErr Then
RowNum = 0
ColNum = 0
Call MsgBox(RngStg & " not recognised as an Excel range", vbOKOnly)
End If
On Error GoTo 0
End Sub
答案 3 :(得分:0)
主要是为了我将来的参考:
public static void Parse( string address )
{
string sheet;
string col;
int row;
int sheetLength = address.IndexOf( '!' );
if ( sheetLength > 0 )
{
sheet = address.Substring( 0, sheetLength );
}
else
{
sheet = string.Empty;
}
++sheetLength; //skip the ! or start at 0
int i = sheetLength;
StringBuilder sb = new StringBuilder( );
for( ; i < address.Length
&& ! Char.IsDigit( address[ i ] )
; ++i )
{
sb.Append( address[ i ] );
}
col = sb.ToString( );
sb.Clear( );
for ( ; i < address.Length
&& Char.IsDigit( address[ i ] )
; ++i )
{
sb.Append( address[ i ] );
}
row = Int32.Parse( sb.ToString( ) );
}
Sinde使用IndexOfAny的方法效率不高,正则表达式解决方案也不是。两种解决方案都忽略了表格。