从字符串中获取倒数第二个字符位置
我有一个动态形成的字符串,如 – part1.abc.part2.abc.part3.abc
在这个字符串中我想知道倒数第二个位置“。” 所以我可以将字符串拆分为part1.abc.part2.abc和part3.abc
让我知道有没有直接的方法来获得这个?
string str = "part1.abc.part2.abc.part3.abc"; int ix1 = str.LastIndexOf('.'); int ix2 = ix1 > 0 ? str.LastIndexOf('.', ix1 - 1) : -1;
总是有Regexes(和jQuery)的爱好者,所以我会提供一个Regex解决方案(对于jQuery解决方案,你必须等待:-)):
var match = Regex.Match(str, @"\.[^\.]*\.", RegexOptions.RightToLeft); int ix = match.Success ? match.Index : -1;
(请注意,我是对正则表达的仇恨 ,我会把它给你,这样你就可以有足够的绳索让自己挂起来,如果你愿意的话)。
请注意,我正在使用RegexOptions.RightToLeft
选项,以便正则表达式从最后一个字符开始。
您可以使用String.LastIndexOf('.')
方法获取最后一个句点/句点的位置,然后在第二次调用LastIndexOf('.')
使用该位置来获取最后一个但是一个,例如:
string aString = "part1.abc.part2.abc.part3.abc"; int lastPos = aString.LastIndexOf('.'); int lastPosButOne = aString.LastIndexOf('.', lastPos - 1);
但我建议使用String.Split('.')
,它会给你一个字符串部分的数组,然后你可以拿最后一个但是一个,例如
string aString = "part1.abc.part2.abc.part3.abc"; string[] parts = aString.Split('.'); string lastPartButOne = parts[parts.Length - 1];
这是另一个解决方案:
string aString = "part1.abc.part2.abc.part3.abc"; // Getting string until last dot var untilLastDot = aString.Substring(0, aString.LastIndexOf(".")); // Now we have string until last dot and last dot here will be last but one // and getting text from last but one dot to end string lastWordButOne = aString.Substring(untilLastDot.LastIndexOf(".") + 1); // Result: part3.abc
希望有所帮助,谢谢!
据我所知,没有开箱即用的解决方案。 一种方法是找到最后一个“。” 使用字符串的LastIndexOf,然后再次搜索最后一个点,这次使用允许您指定startindex和count的重载,使用第一个调用的索引作为计数参数。
您可以使用String.Split()
方法,该方法返回已String.Split()
项的数组。 然后,您可以连接前2个并保留最后一个。
尝试字符串类LastIndexOf方法。
怎么样"part1.abc.part2.abc.part3.abc".Split('.')
在这种情况下你会得到一个包含所有子串的数组
希望这可以帮助。
LastIndexOf应该做你想要的。 做两次。
根据@bitbonk的回答。 我使用下面的代码,它是VFP
的RAT()
函数的副本。
public static int RightIndexAt(this string expressionToSearch, char charToSearch, int occurence) { //Validate parameter if (occurence < 1) return -1; int index = -1; int numfound = 0; for (int count = expressionToSearch.Length - 1; count >= 0; count--) { if (expressionToSearch[count].Equals(charToSearch)) { index = count; numfound++; } if (numfound.Equals(occurence)) break; } return numfound < occurence ? -1 : index; }
这将是解决方案,具有最佳性能(它可能不会比这更快和内存轻量级,除非你想要走不安全路线):
public static int LastIndexOf(this string str, char charToSearch, int repeatCound) { int index = -1; for(int i = str.Length - 1; i >= 0, numfound < repeatCound) { if(str[i] == charToSearch) { index = i; numfound++; } } return index; }