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

本文关键字:返回 然后 余部 文本 字符串 查找 | 更新日期: 2023-09-27 18:25:32

我正在尝试这样做:

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"

谢谢。

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

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

        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?

您应该尝试类似的东西

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");
var foo = "Hello, this is a string";
Console.WriteLine(foo.Substring(0,2));
Console.WriteLine(foo.Substring(2));

结果:

//He
//llo, this is a string

如果你需要一直这样做,你可以创建一个扩展方法并这样调用它

扩展方法:

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