Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string into two variables after specific length [closed]

Tags:

c#

I need to split a string into two string variables at a specific length, more exactly after the first two characters.

Example 1: XX123456789 should be split into:

  • val1: XX
  • val2: 123456789

Example 2: string NN125457878 should be split into:

  • val1: NN
  • val2: 125457878
like image 232
user2818430 Avatar asked May 25 '26 02:05

user2818430


2 Answers

You can use String.Substring(Int32) and String.Substring(Int32, Int32) overloads like;

string s = "XX123456789";
string val1 = s.Substring(0, 2);
string val2 = s.Substring(2);
Console.WriteLine(val1);
Console.WriteLine(val2);

Prints;

XX
123456789

Here a demonstration.

like image 111
Soner Gönül Avatar answered May 27 '26 16:05

Soner Gönül


You would use the Substring method.

For the first one, you would specify the start index of 0, with a length of 2. For the second one, you would use a start index of 2 and no length, which will return everything in the string from the third character until the end.

See the MSDN Documentation.

var theString = "XX123456789";
var val1 = theString.Substring(0, 2);
var val2 = theString.Substring(2);
like image 29
Tim S Avatar answered May 27 '26 15:05

Tim S



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!