我有一个字符串:
string mystring="part1, part2, part3, part4, part5";
如何在不先拆分的情况下返回前3个元素? 像这样:
string newstring="part1, part2, part3";
答案 0 :(得分:1)
你可以使用前三个:
RegEx r = new RegEx(@“(\ S +,\ S +,\ S +),\ S +”);
我确信有更好的方法可以编写正则表达式,但我认为这样做可以用于基本输入。
答案 1 :(得分:0)
尝试找到第三个逗号的索引,然后获取子字符串。
实施例
void Main()
{
string mystring="part1, part2, part3, part4, part5";
int thirdCommaIndex = IndexOf(mystring, ',', 3);
var substring = mystring.Substring(0,thirdCommaIndex-1);
Console.WriteLine(substring);
}
int IndexOf(string s, char c, int n)
{
int index = 0;
int count = 0;
foreach(char ch in s)
{
index++;
if (ch == c)
count++;
if (count == n )
break;
}
if (count == 0) index = -1;
return index;
}
答案 2 :(得分:0)
这将解析字符串,试图找到第三个逗号并将其抛弃,然后抛弃它。
string mystring = "part1, part2, part3, part4, part5";
UInt16 CommasFound = 0;
UInt16 Location = 0;
for (Location = 0; (CommasFound < 3) &&
(Location < mystring.Count()); Location++)
if (mystring[Location].Equals(','))
CommasFound++;
if (CommasFound == 3)
{
string newstring = mystring.Substring(0, Location-1);
}
else { // Handle the case where there isn't a third item
}