Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ionic-framework/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何删除特定字符之前字符串中的所有字符_C#_String_Substring_Trim - Fatal编程技术网

C# 如何删除特定字符之前字符串中的所有字符

C# 如何删除特定字符之前字符串中的所有字符,c#,string,substring,trim,C#,String,Substring,Trim,假设我有一个字符串a,例如: string A = "Hello_World"; 我想删除之前(包括)的所有字符。前的确切字符数可能会有所不同。在上面的示例中,删除后,A==“World” var foo = str.Substring(str.IndexOf('_') + 1); 试试这个?或者您的A=Hello\u世界中的A=部分是否包括在内?您已经收到。如果您愿意更进一步,您可以将a.SubString(a.IndexOf(“”“)+1)封装在一个健壮灵活的扩展方法中: string

假设我有一个字符串
a
,例如:

string A = "Hello_World";
我想删除
之前(包括)的所有字符。
前的确切字符数可能会有所不同。在上面的示例中,删除后,
A==“World”

var foo = str.Substring(str.IndexOf('_') + 1);
试试这个?或者您的A=Hello\u世界中的A=部分是否包括在内?

您已经收到。如果您愿意更进一步,您可以将
a.SubString(a.IndexOf(“”“)+1)
封装在一个健壮灵活的扩展方法中:

string A = "Hello_World";
string str = A.Substring(A.IndexOf('_') + 1);
public static string TrimStartUpToAndIncluding(this string str, char ch)
{
    if (str == null) throw new ArgumentNullException("str");
    int pos = str.IndexOf(ch);
    if (pos >= 0)
    {
        return str.Substring(pos + 1);
    }
    else // the given character does not occur in the string
    {
        return str; // there is nothing to trim; alternatively, return `string.Empty`
    }
}
您会像这样使用它:

"Hello_World".TrimStartUpToAndIncluding('_') == "World"

可以通过创建子字符串来实现这一点

简单的例子如下:

publicstaticstringremovetillword(字符串输入,字符串字){
返回input.substring(input.indexOf(word));
}
removeTillWord(“我需要删除此词,请删除”、“删除”)
public static string TrimStartUpToAndIncluding(this string str, char ch)
{
    if (str == null) throw new ArgumentNullException("str");
    int pos = str.IndexOf(ch);
    if (pos >= 0)
    {
        return str.Substring(pos + 1);
    }
    else // the given character does not occur in the string
    {
        return str; // there is nothing to trim; alternatively, return `string.Empty`
    }
}
"Hello_World".TrimStartUpToAndIncluding('_') == "World"