2013-04-16 63 views

回答

9

喜歡的東西如下:

string originalStr = "C:\\Test-Processed\\1-Processed\\2-Processed"; 
string temp = "-Processed"; 
string str = originalStr.Substring(0, originalStr.IndexOf(temp) + temp.Length); 
originalStr = str + originalStr.Substring(str.Length).Replace(temp, ""); 

originalStr將是:

originalStr = "C:\\Test-Processed\\1\\2" 
+2

這是一個很酷的答案 – Patashu

+2

爲真棒解決方案。 –

1

事情是這樣:

String str = @"C:\\Test-Processed\1-Processed\2-Processed"; 
System.Console.WriteLine(new Regex("(\\d+)-Processed").Replace(str, "$1")); 

將產生C:\\Test-Processed\1\2。正則表達式假定您要刪除的元素始終在一個或多個數字前面。它會將這些數字放入一個捕獲組中,並且只用數字(1)替換子字符串(示例1-處理過的)。

編輯:如果假設失敗,你可能要採取@Patashu建議的方法。

4

這裏的關鍵洞察是indexOf的存在,它開始在字符串的某個點搜索字符串,而不是從開始搜索。這裏:http://msdn.microsoft.com/en-us/library/7cct0x33.aspx

首先,您要使用.indexOf("-Processed")找到字符串中第一個索引-Processed。記住這個索引。

現在,使用.indexOf("-Processed", index+1)找到-Processed這不是第一個的下一個索引。

重複這個和Substring(nextindex, "-Processed".Length)刪除這些額外的實例,直到你找不到更多。

1
string ReplaceExceptFirst(string text, string search, string replace) 
{ 
    int pos = text.IndexOf(search); 
    if (pos < 0) 
    { 
     return text; 
    } 

    int strlen = pos + search.Length; 
    return text.Substring(0, strlen) + (text.Substring(strlen)).Replace(search,replace); 
} 
0

這是上面給出的解決方案之一。 (由Habib提供的解決方案和由Pintu Paul提供的參數命名)。我用它,但隨後將函數定義爲字符串擴展。


public static class StringExtensions 
{ 
    public static string ReplaceAllButFirst(this string originalStr, string search, string replace) 
    { 
     string str = originalStr.Substring(0, originalStr.IndexOf(search, System.StringComparison.InvariantCultureIgnoreCase) + search.Length); 
     return str + originalStr.Substring(str.Length).Replace(search, replace); 
    } 
} 
相關問題