0

我是 C# 新手,请帮助以高效的 C# 方式编写。

案例(总是第一个字符是'-',最后一个是'>'):

示例 1:

input:   bdfdfd-wr>
output:  wr

示例 2:

input:   -dsdsds-sdsds-grtt>
output:  grtt

示例 3:

input:   -dsdsds-sdsds-grtt>><>>dfdfdfd
output:  grtt

示例 4:

input:   -dsdsds-sdsds-grtt>><->>df-d=fdfd
output:  grtt
4

6 回答 6

2
string example = "-dsdsds-sdsds-grtt>";
int lastIndexOfHyphen = example.LastIndexOf("-");
int indexOfBracket = example.IndexOf(">", lastIndexOfHyphen);
string substr = example.Substring(lastIndexOfHyphen + 1, indexOfBracket - lastIndexOfHyphen - 1);
于 2012-09-11T12:49:16.550 回答
1

LINQ 风格:

var output = input.Split('>').First().Split('-').Last();
于 2012-09-11T16:29:42.147 回答
1

我可以想到两种方法:

于 2012-09-11T12:49:19.133 回答
1

您可以使用正则表达式


例子:

var r = new Regex(@"-(\w*)>");

var inputs = new [] { "bdfdfd-wr>",
                      "-dsdsds-sdsds-grtt>",
                      "-dsdsds-sdsds-grtt>><>>dfdfdfd",
                      "-dsdsds-sdsds-grtt>><->>df-d=fdfd" };

foreach(var i in inputs)
    Console.WriteLine(r.Match(i).Groups[1].Value);

输出:

wr
grtt
grtt
grtt

于 2012-09-11T12:49:56.013 回答
1
        string s = "-dsdsds-sdsds-grtt>";
        string output = null;
        if (s.Contains(">"))
        {
            output = s.Split(new string[] { ">" }, 
                             StringSplitOptions.RemoveEmptyEntries)
                      .FirstOrDefault(i => i.Contains("-"));
            if (output != null)
                output = output.Substring(output.LastIndexOf("-") + 1);
        }

返回包裹在 - 和 > 中的第一行文本。如果输入的是"-dsdsds-sdsds-grtt>asdas-asq>",它会返回grtt;for -dsdsds-sdsds-grtt>><>>dfdfdfd-grtt也返回

在那里你可以找到很多处理字符串的方法。

于 2012-09-11T12:52:54.013 回答
1
     string input = "-dsdsds-sdsds-grtt>";
     int startInd = input.LastIndexOf('-');
     int endInd = input.IndexOf('>', startInd);
     string result;
     if (startInd < endInd) 
         result = input.Substring(startInd + 1, endInd - startInd - 1);

编辑:

    string input = "-dsdsds-sdsds-grtt>><->>df-d=fdfd";
    string str = input.Substring(0, input.IndexOf('>'));
    string result = str.Substring(str.LastIndexOf('-') + 1);

使用 linq 似乎也是一个不错的选择:

var result = input.Split('>').First().Split('-').Last();
于 2012-09-11T12:52:54.730 回答