C#在字符串中查找文本然后返回其余部分

时间:2015-12-04 01:45:17

标签: c# string substring

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

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"

感谢。

3 个答案:

答案 0 :(得分:0)

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

        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?

答案 1 :(得分:0)

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 :(得分:0)

你应该尝试这样的事情

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");