简体   繁体   中英

How do I split a String into 2 different types?

I have a string "201607" and I need to split it to 2 separate types. 2016 into int and 07 into byte. I have seen string split functions which all use delimeters but that won't work here. Is there an easier way to do this or so I have to split it into chars and then reconstruct them in C#?

Try it also:

string input="201607";
int IntPart=Convert.ToInt32(input.Substring(0,4));
byte BytePart=Convert.ToByte(input.Substring(4));

Try this Example

string input="201607";
int integerPart=0;      
if(int.TryParse(input.Substring(0,4),out integerPart))
{
    Console.WriteLine("Integer value is {0}",integerPart);
}
else
{
    Console.WriteLine("Conversion Failed");
}
byte bytePart = byte.Parse(input.Substring(4));
Console.WriteLine("Byte Part is {0}",bytePart);

Perhaps try this too:

var input = "201607";
var matches = Regex.Match(input, "(\\d{4})(\\d{2})");
var integerPart = int.Parse(matches.Groups[1].Captures[0].Value);
var bytePart = byte.Parse(matches.Groups[2].Captures[0].Value);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM