2011-03-15 82 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