2011-03-15 50 views

回答

26

可以使用

str = str.SubString (10); // to remove the first 10 characters. 
str = str.Remove (0, 10); // to remove the first 10 characters 
str = str.Replace ("NT-DOM-NV\\", ""); // to replace the specific text with blank 

// to delete anything before \ 

int i = str.IndexOf('\\'); 
if (i >= 0) str = str.SubString(i+1); 
+0

我认为重点是这个工作在几个不同的字符串上,以便他有两个字符串,并且想要从另一个字符串中删除一个字符串。 – 2011-03-15 13:16:16

+0

@ØyvindKnobloch-Bråthen,已经增加了更多的选择。 – 2011-03-15 13:19:21

+0

我没有要求删除前10个字符! – SamekaTV 2011-03-15 13:21:02

3

如果永远只有一个反斜杠,使用此:

string result = yourString.Split('\\').Skip(1).FirstOrDefault(); 

如果可以有多个,你只希望有最后一部分,使用此:

string result = yourString.SubString(yourString.LastIndexOf('\\') + 1); 
+0

+1简洁且可重复使用 – JohnK813 2011-03-15 13:18:37

0
string s = @"NT-DOM-NV\MTA"; 
s = s.Substring(10,3); 
+1

-1:他从未指定,任何一个部分的长度都是固定的。 – 2011-03-15 13:17:47

+0

@丹尼尔:公平地说,他没有指出太多......可能没有“\” – 2011-03-15 13:20:16

+0

@paolo:你是对的。但假设任何这些字符串都是固定长度的,可能在30年前是正确的,但现在不是。 – 2011-03-15 13:22:02

1

尝试

string string1 = @"NT-DOM-NV\MTA"; 
string string2 = @"NT-DOM-NV\"; 

string result = string1.Replace(string2, ""); 
+0

string result = string1.Replace(string2,string.Empty); – katta 2014-09-05 20:17:26

4
string.TrimStart(what_to_cut); // Will remove the what_to_cut from the string as long as the string starts with it. 

"asdasdfghj".TrimStart("asd" );将导致"fghj"
"qwertyuiop".TrimStart("qwerty");将导致"uiop"


public static System.String CutStart(this System.String s, System.String what) 
{ 
    if (s.StartsWith(what)) 
     return s.Substring(what.Length); 
    else 
     return s; 
} 

"asdasdfghj".CutStart("asd" );现在将产生"asdfghj"
"qwertyuiop".CutStart("qwerty");仍然会导致"uiop"

+1

有线问题。我认为很多开发人员不知道这一点。无论如何,这是非常好的解决方案,我将我们应用程序中的所有TrimStart替换为CutStart方法。谢谢。 – Jacob 2017-08-13 22:20:58

9

鉴于 “\” 总是出现在字符串中

var s = @"NT-DOM-NV\MTA"; 
var r = s.Substring(s.IndexOf(@"\") + 1); 
// r now contains "MTA" 
+0

这正是我所需要的!谢谢。 – SamekaTV 2011-03-15 13:24:26

+0

如果字符串是“@”NT-DOM-NV \ MTA \ ABC \ file“',并且在分割”NT-DOM-NV“后,我需要分割后的第一个字符串。在这种情况下,它应该是'MTA'。如果我必须分割“NT-DOM-NV \ MTA”,那么它应该返回“ABC”。 TIA – ASN 2016-06-22 09:32:26

0

您可以使用此扩展方法:

public static String RemoveStart(this string s, string text) 
{ 
    return s.Substring(s.IndexOf(s) + text.Length, s.Length - text.Length); 
} 

在你的情况,你可以使用它,如下所示:

string source = "NT-DOM-NV\MTA"; 
string result = source.RemoveStart("NT-DOM-NV\"); // result = "MTA" 

注意:做不是使用TrimStart方法为i t可能会进一步修剪一个或多个字符(see here)。

0
Regex.Replace(@"NT-DOM-NV\MTA", @"(?:[^\\]+\\)?([^\\]+)", "$1") 

试一试here