如何得到字符串的最后两个部分,用,隔开

本文关键字:两个 隔开 何得 字符串 最后 | 更新日期: 2023-09-27 18:12:28

我在c#中有一些这样的字符串:

interesting, fun, May 08, 2012
this is very interesting text, June 19, 2011

我想要得到两个字符串,一个包含日期,另一个包含所有字符串

所以输出应该是这样的:

string1=interesting, fun
string2=May 08, 2012
string1=this is very interesting text
string2=June 19, 2011

谢谢你的提示

如何得到字符串的最后两个部分,用,隔开

好吧,我知道有比这更好的方法(比如使用Regex),但这里有一种快速而肮脏的方法:

string str1 = "blah, blah, May 08, 2012";
string str2 = "blah blah blah, June 19, 2011";
int splitter = str1.Substring(0, str1.LastIndexOf(',')).LastIndexOf(',');
string newStr1 = str1.Substring(0, splitter);
string newStr2 = str1.Substring(splitter + 2, str1.Length - (splitter + 2));
Console.WriteLine(newStr1);
Console.WriteLine(newStr2);
Console.ReadKey();
bool foundDateComma = false;
string beginning, date;
for (int i = s.Length - 1; i >= 0; i--)
    if (s[i] == ',')
        if (!foundDateComma)
            foundDateComma = true;
        else
        {
            beginning = s.Substring(0, i);
            date = s.Substring(i + 1);
            break;
        }

正则表达式可以帮助你:

Match match = Regex.Match(yourstring, @"[January|February|March|April|May|June|July|August|September|October|November|December]'s'd+,'s'd+");
string date = match.Groups[1].Value;
string blah = yourstring.Substring(0, yourstring.IndexOf(date) -1);

您可以使用正则表达式,如:

.*,(.*,'s*'d+)$

这将创建一个匹配组:

June 19, 2011

它将匹配任何字符,后面跟着逗号,后面跟着数字,最后是字符串的结尾。

示例