我的主要字符串是,
“自 1500 年代以来,Lorem Ipsum 一直是行业标准的虚拟文本 20 TN 123 34”
我只想从主字符串中获取“123 34”。 我已经通过以下代码完成了。
string mainStr = " Lorem Ipsum has been the industry's standard dummy text ever since the 1500s 20 TN 123 34";
string filterStr = mainStr.Substring(0, mainStr.LastIndexOf(" "));
int sRange = filterStr.LastIndexOf(" ");
string outputStr = mainStr.Substring(sRange+1);
如何通过Linq方式完成(单行就很棒)?
最佳答案
使用 linq 获取最后两个元素可能有点不可读,因此我建议使用不包含 LastIndexOf
或 Substring
的多行解决方案:
string mainStr = " Lorem Ipsum has been the industry's standard dummy text ever since the 1500s 20 TN 123 34";
var words = mainStr.Split();
var lastTwoWords = string.Join(" ", words.Skip(words.Length - 2));
如果你真的需要它是 linq,你可以使用 Reverse
和 Take
的组合:
var lastTwoWords = string.Join(" ", mainStr.Split().Reverse().Take(2).Reverse());
关于c# - 如何从字符串中获取最后 2 个单词(从倒数第二个空格开始)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54586181/