简体   繁体   English

如何根据字母和数字在C#中拆分字符串

[英]How do I split a string in C# based on letters and numbers

How can I split a string such as "Mar10" into "Mar" and "10" in c#? 如何在c#中将“Mar10”等字符串拆分为“Mar”和“10”? The format of the string will always be letters then numbers so I can use the first instance of a number as an indicator for where to split the string. 字符串的格式将始终是字母然后是数字,因此我可以使用数字的第一个实例作为分割字符串的位置的指示符。

You could do this: 你可以这样做:

var match = Regex.Match(yourString, "(\w+)(\d+)");
var month = match.Groups[0].Value;
var day = int.Parse(match.Groups[1].Value);

You are not saying it directly, but from your example it seems are you just trying to parse a date. 你不是直接说,但从你的例子来看,你似乎只是想解析一个约会。

If that's true, how about this solution: 如果这是真的,那么这个解决方案怎么样:

DateTime date;
if(DateTime.TryParseExact("Mar10", "MMMdd", new CultureInfo("en-US"), DateTimeStyles.None, out date))
{
    Console.WriteLine(date.Month);
    Console.WriteLine(date.Day);
}
char[] array = "Mar10".ToCharArray();
int index = 0;
for(int i=0;i<array.Length;i++)
{
   if (Char.IsNumber(array[i]){
      index = i;
      break;
   }
}

Index will indicate split position. 索引将指示拆分位置。

var match = Regex.Match(yourString, "([|A-Z|a-z| ]*)([\d]*)");
var month = match.Groups[1].Value;
var day = int.Parse(match.Groups[2].Value);

I tried Konrad's answer above, but it didn't quite work when I entered it into RegexPlanet. 我在上面尝试了Konrad的答案,但是当我进入RegexPlanet时,它并没有完全奏效。 Also the Groups[0 ] returns the whole string Mar10 . Groups[0 ]也返回整个字符串Mar10 You want to start with Groups[1] , which should return Mar and Groups[2] should return 10 . 你想从Groups[1]开始, Groups[1]应返回MarGroups[2]应返回10

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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