【问题标题】:C# find text in a string then return the restC# 在字符串中查找文本,然后返回其余部分
【发布时间】:2016-03-08 20:49:29
【问题描述】:

我正在尝试做这样的事情:

string foo = "Hello, this is a string";
//and then search for it. Kind of like this
string foo2 = foo.Substring(0,2);
//then return the rest. Like for example foo2 returns "He".
//I want it to return the rest "llo, this is a string"

谢谢。

【问题讨论】:

  • 将其更改为foo.Substring(2);。完成。

标签: c# string substring


【解决方案1】:
var foo = "Hello, this is a string";
Console.WriteLine(foo.Substring(0,2));
Console.WriteLine(foo.Substring(2));

结果:

//He
//llo, this is a string

如果您一直需要这样做,您可以创建一个Extension Method 并像这样调用它。

扩展方法:

public static class Extensions
{
    public static Tuple<string, string> SplitString(this string str, int splitAt)
    {
        var lhs = str.Substring(0, splitAt);
        var rhs = str.Substring(splitAt);
        return Tuple.Create<string, string>(lhs, rhs);
    }   
}

像这样使用扩展方法:

var result = foo.SplitString(2);
Console.WriteLine(result.Item1);
Console.WriteLine(result.Item2);

结果:

//He
//llo, this is a string

【讨论】:

    【解决方案2】:

    你应该试试这样的

    public string FindAndReturnRest(string sourceStr, string strToFind)
    {
        return sourceStr.Substring(sourceStr.IndexOf(strToFind) + strToFind.Length);
    }
    

    然后

    string foo = "Hello, this is a string";
    string rest = FindAndReturnRest(foo, "He");
    

    【讨论】:

      【解决方案3】:

      我认为你应该澄清规则,当另一个字符串时你想要什么。

              string foo = "Hello, this is a string";
              int len1 = 2; // suppose this is your rule
              string foo2 = foo.Substring(0, len1);
              string foo3 = foo.Substring(len1, foo.Length - len1); //you want this?
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-20
        • 1970-01-01
        • 2015-08-22
        相关资源
        最近更新 更多