usr021986 usr021986 - 2 months ago 12
C# Question

Better way to split a string "a_b_c_d.1.2.3.4"

what is the best ways to split sting "aaa_bx_cd_de.1000.20.3.40" to "aaa_bx_cd_de" and "1000.20.3.40" in C#.net application

mainstring="aaa_bx_cd_de.1000.20.3.40"
str1="aaa_bx_cd_de"
str2="1000.20.3.40"

Answer

You can use an overload of String.Split[1] that takes as a second argument the number of substrings you want returned (essentially the number of splits plus 1).

string mainstring = "a_b_c_d.1.2.3.4";
string[] parts = string.Split(new [] {'.'}, 2);
// parts[0] will be "a_b_c_d"
// parts[1] will be "1.2.3.4"

[1] https://msdn.microsoft.com/en-us/library/c1bs0eda(v=vs.110).aspx

Comments