i have string col= "AB21"
which is an excel cell location.
I would like to parse it as string column = "AB"
& int row = 21;
How can i do that?
Split cellsIn the table, click the cell that you want to split. Click the Layout tab. In the Merge group, click Split Cells. In the Split Cells dialog, select the number of columns and rows that you want and then click OK.
Click in a cell, or select multiple cells that you want to split. Under Table Tools, on the Layout tab, in the Merge group, click Split Cells. Enter the number of columns or rows that you want to split the selected cells into.
If this was Excel I would rely on Excel since the definition of a valid range depends on the version. Unlike the previous answers, this routine will reject strings that look like ranges but are not valid ranges such as, with Excel 2003, "XB21" or "AB66000". I assume the function below can be converted to 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
string col = "AB21";
int startIndex = col.IndexOfAny("0123456789".ToCharArray());
string column = col.Substring(0, startIndex);
int row = Int32.Parse(col.Substring(startIndex));
Of course, you should guarantee that input string will be in correct format.
One option you have is to use a regex to validate and parse the input string. See the code below.
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");
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With