You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

C#:如何提取指定格式字符串中的倒数第二个元素

解决提取字符串倒数第二个元素的问题

Hey there! Let's get this sorted for you. The core issue with your current code is that it's grabbing everything from the first -> to just before ->val, but what you actually need is the second-to-last element in that chain—no matter how many elements are in the string.

方法一:用Split分割(推荐,简洁易读)

Since your string uses a consistent separator ->, the easiest way is to split the string into an array of parts, then pick the element at index length - 2 (arrays are zero-indexed, so this gives us the second-to-last item).

Here's the updated code:

string path = "Value->Value2->Value3->ImportantValue->val";
// Split the string using "->" as the separator
string[] parts = path.Split(new[] {"->"}, StringSplitOptions.None);
// Grab the second-to-last element
string importantValue = parts[parts.Length - 2];

For your example input, this will give you exactly ImportantValue. Even if you add more elements to the front (like A->B->Value->Value2->...->val), this code still works perfectly because it always targets the second-to-last part of the split array.

方法二:用IndexOf定位(适合不想用Split的场景)

If you prefer to stick with string indexing instead of splitting, you can find the positions of the last two -> separators and extract the text between them:

string path = "Value->Value2->Value3->ImportantValue->val";
// Find the position of the last "->"
int lastSeparator = path.LastIndexOf("->");
// Find the position of the second-to-last "->" (search before the last one)
int secondLastSeparator = path.LastIndexOf("->", lastSeparator - 1);
// Extract the text between these two separators
string importantValue = path.Substring(
    secondLastSeparator + "->".Length,
    lastSeparator - (secondLastSeparator + "->".Length)
);

This works by narrowing down the exact range where your target value sits, avoiding the mistake of starting from the first separator.

Either method will reliably get you the dynamic ImportantValue you need, no matter how long the string grows.

内容的提问来源于stack exchange,提问作者Mysterio

火山引擎 最新活动