从c#中的给定String获取值 [英] Get Value from given String in c#

查看:95
本文介绍了从c#中的给定String获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里我有两根琴弦



01/19/2016 110056234 283 4



1月11日2016 3:01 PM 110056234 283 4



01/19/2016 11234 283 4



我需要从上面的字符串中获取值(283),所有代码都相同。任何人都可以帮助我吗?

Here i have two strings

01/19/2016 110056234 283 4

Jan 11 2016 3:01PM 110056234 283 4

01/19/2016 11234 283 4

I need to get the value(283) from above strings with same code for all. Can any one help me?

推荐答案

这很简单:使用空格作为分隔符拆分字符串并获取结果数组的最后一项。
That's simple: split the strings using blank as separator and get the last but one item of the resulting array.


解决此问题的一种方法(RegEx除外)是编写字符串扩展方法:
One way to approach this (other than RegEx) is to write a String Extension method:
public static class StringExtensions
{
    public static string FromNextToLastToLast(this string source, string delimiter)
    {
        int last = source.LastIndexOf(delimiter);
        int nexttolast = source.Substring(0, last).LastIndexOf(delimiter);

        if (last == 0) return String.Empty;

        return source.Substring(nexttolast + 1, last - nexttolast - 1);
    }
}

测试:

List<string> testStrings = new List<string>
{
    " 01/19/2016 110056234",

    "01/19/2016 110056234 283 4",

    "Jan 11 2016 3:01PM 110056234 283 4",

    "01/19/2016 11234 283 4",

    "01/19/2016 110056234 455 43"
};

private void button2_Click(object sender, EventArgs e)
{
    string result;

    foreach (string str in testStrings)
    {
        result = str.FromNextToLastToLast(" ");

        Console.WriteLine("source: \"{0}\" : result: \"{1}\"", 
            str, 
            (result == string.Empty) ? "String.Empty" : result);
    }
}

// results in Console:
source: "01/19/2016 110056234" : result: "String.Empty"
source: "01/19/2016 110056234 283 4" : result: "283"
source: "Jan 11 2016 3:01PM 110056234 283 4" : result: "283"
source: "01/19/2016 11234 283 4" : result: "283"
source: "01/19/2016 110056234 455 43" : result: "455"


这篇关于从c#中的给定String获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆