C# 使用第一个空格从右侧获取值

C# 使用第一个空格从右侧获取值,c#,.net,string,C#,.net,String,我想从随机字符串的右边得到第一个空格的值,如下所示 if my 1. string = "sdsd sdsd sdsd 3232323" or 2. string = "sdsd sdsd dseee3232323" or 3.string = "sdsd dseee3232323" or 4.string = "sdsd dseee3232323" output : 1. 3232323 2. dseee3232323 3. dseee3232323 4. dseee3232323 使用

我想从随机字符串的右边得到第一个空格的值,如下所示

if my 
1. string = "sdsd sdsd sdsd 3232323"
or
2. string = "sdsd sdsd dseee3232323"
or
3.string = "sdsd dseee3232323"
or
4.string = "sdsd dseee3232323"

output :
1. 3232323
2. dseee3232323
3. dseee3232323
4. dseee3232323
使用和,就像这样:

 var result = s.Split(' ').LastOrDefault();
只是别忘了先在using指令中添加以下内容:

using System.Linq;
方法:


Linq不是必需的

String result = "";
String[] tempArray = workString.Split(' ');
if (tempArray.Length > 1)
     String result = temparray[tempArray.Length-1];
拆分为一个数组并查看最后一个元素。我不建议您在学习基础知识之前使用linq


此外,我还添加了一个检查,以查看结果是否无效(没有空格)。如果没有空格,其他答案将返回整个字符串。

对于这个示例“asd asd123 asd”,输出是什么?“asd123 asd”或“asd123”请显示您到目前为止的尝试,即使像您这样不正确的书籍混淆了“空格”和“空白”…我尝试了这个在空字符串上失败的方法?@dfhwze否,它返回空字符串OP询问的是空白字符而不是空格字符。无论是正则表达式还是空白字符列表,都是正确的解决方案。。
String result = "";
String[] tempArray = workString.Split(' ');
if (tempArray.Length > 1)
     String result = temparray[tempArray.Length-1];