【问题标题】:Extract The Last Part (Section) of a String [duplicate]提取字符串的最后一部分(部分)[重复]
【发布时间】:2015-12-12 10:57:06
【问题描述】:

我只需要在/ 字符之后提取字符串的最后一部分。

我试过LastIndexOf,但失败了。

有什么办法吗?


尝试

var strDiv2 = tbxAff.Substring(tbxAff.IndexOf(" / "), /*value is missing*/ );
dblDiv2 = Convert.ToDouble(strDiv2);`
        

【问题讨论】:

  • 欢迎来到 Stackoverflow!请编辑您的问题并在此处插入 C# 代码。但是,这个stackoverflow.com/questions/15667927/… 会帮助你。
  • 将您的代码发布为文本,不是图像。这将大大提高您获得答案的机会。此外,您可以从 TextBox 获取文本,因此您的问题实际上是“提取字符串的最后一部分
  • 您的问题与TextBoxes无关,将字符串开箱即用并使用字符串函数对其进行操作。你试过 string.Split 吗?
  • LastIndexOf 是去这里的方式,向我们展示您对 LastIndexOf 的尝试
  • 你得到什么错误信息?

标签: c# .net extract indexof


【解决方案1】:

您可以省略第二个参数。这将调用Substring(int) 重载,它返回一个从指定字符位置开始并一直到字符串末尾的子字符串。

string strDiv2 = tbxAff.Text.Substring(tbxAff.Text.IndexOf("/") + 1);

此外,如果您将提取的子字符串解析为双精度字符串,您可能希望排除 / 分隔符。

【讨论】:

    【解决方案2】:

    使用String.Split()函数:

    string[] y = tbxAff.Text.Split(new string[] { " / " }, StringSplitOptions.RemoveEmptyEntries);
    

    然后像这样使用它:

    string strDiv2 = y[1] // Second Part
    dblDiv2 = Convert.ToDouble(strDiv2);
    

    【讨论】:

      【解决方案3】:

      string clientSpnd = textBox1.Text.Substring(textBox1.Text.LastIndexOf(' ') + 1);

      【讨论】:

        【解决方案4】:

        这是一个扩展方法,它会进行安全检查:

        public static class StringExtensions
        {
             public static string LastPartOfStringFrom(this string str, char delimiter )
             {
                 if (string.IsNullOrWhiteSpace(str)) return string.Empty;
        
                 var index = str.LastIndexOf(delimiter);
        
                 return (index == -1) ? str : str.Substring(index + 1);
             }
        }
        

        【讨论】:

          猜你喜欢
          • 2022-09-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-03-28
          • 2014-12-11
          • 1970-01-01
          相关资源
          最近更新 更多