【问题标题】:Get value from right with first white space使用第一个空格从右侧获取值
【发布时间】:2019-07-09 03:41:43
【问题描述】:

我想从随机字符串的右侧获取第一个空格的值,如下所示。

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

【问题讨论】:

  • 给出这个例子“asd asd123 asd”会是什么输出? “asd123 asd”或“asd123”
  • 请显示您迄今为止的尝试,即使不正确
  • 看起来你混淆了“空格”和“空白”..

标签: c# .net string


【解决方案1】:

LastIndexOf方法:

string s = "sdsd sdsd sdsd 3232323";
var result = s.Substring(s.LastIndexOf(' ') + 1);

【讨论】:

  • 我试过了,谢谢
  • 空字符串失败?
  • @dfhwze 不,它返回空字符串
  • OP 询问了空格而不是空格字符。正则表达式或空白字符列表都是正确解决方案的要求..
【解决方案2】:

使用SplitLastOrDefault,就像这样:

 var result = s.Split(' ').LastOrDefault();

请不要忘记首先将以下内容添加到您的 using 指令中:

using System.Linq;

【讨论】:

    【解决方案3】:

    Linq 不是必需的。

    String result = "";
    String[] tempArray = workString.Split(' ');
    if (tempArray.Length > 1)
         String result = temparray[tempArray.Length-1];
    

    拆分成一个数组,查看最后一个元素。在您了解基础知识之前,我不建议您使用 linq。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-16
      • 2012-10-23
      • 2012-06-24
      • 2011-03-27
      • 2015-10-29
      • 2015-05-02
      相关资源
      最近更新 更多