2016-06-13 195 views
1

我哈瓦,我想更換在C#替換字符串

string gerneralRootPath = docTab.Rows[0]["URL"].ToString(); 
string documentName = docTab.Rows[0]["NAME"].ToString(); 

var connectNamesAndURL = new StringBuilder(gerneralRootPath); 
connectNamesAndURL.Remove(30,20); 
connectNamesAndURL.Insert(30, documentName); 
gerneralRootPath = connectNamesAndURL.ToString(); 

gerneralRootPath的輸出是 「文件/ Z_Do​​cumentation/PDF/sales.2010 +實施+修+ Feb10.pdf」 的特定字符串

的是documentName輸出是 「doc123」

我戈萊是消除一切後/ PDF/..所以日在最終的字符串看起來像 文件/ Z_Do​​cumentation/PDF/doc123

所以,我怎麼能去掉一切/ PDF/..

回答

1

試試這個

string gerneralRootPath = "Documents/Z_Documentation/PDF/sales.2010+Implementation+Revised+Feb10.pdf"; 
gerneralRootPath = gerneralRootPath.Remove(gerneralRootPath.IndexOf("PDF") + 3); 
gerneralRootPath = gerneralRootPath +"/"+documentName ; 
+0

TNX該配發很棒! – SuperDoc

+0

不客氣 – Mairaj

0

後,您可以做到這一點使用String.Split()功能:

string input = "Documents/Z_Documentation/PDF/sales.2010+Implementation+Revised+Feb10.pdf"; 
string output = input.Split(new string[] { "/PDF/" }, StringSplitOptions.None).First() + "/PDF/doc123"; 
0

這是一個例子:

class Program 
{ 
    static string RemoveAfterPDF(string gerneralRootPath) 
    { 
     string pdf = "PDF"; 
     int index = gerneralRootPath.IndexOf(pdf); 
     return gerneralRootPath.Substring(0, index + pdf.Length); 
    } 

    public static void Main() 
    { 
     string test = RemoveAfterPDF("Documents/Z_Documentation/PDF/sales.2010+Implementation+Revised+Feb10.pdf"); 
    } 
} 

編輯 這是更好和更可重複使用的例子:

class Program 
{ 
    static string RemoveAfter(string gerneralRootPath, string removeAfter) 
    { 
     string result = string.Empty; 
     int index = gerneralRootPath.IndexOf(removeAfter); 

     if (index > 0) 
      result = gerneralRootPath.Substring(0, index + removeAfter.Length); 

     return result; 
    } 

    public static void Main() 
    { 
     string test = RemoveAfterPDF("Documents/Z_Documentation/PDF/sales.2010+Implementation+Revised+Feb10.pdf", "PDF"); 
    } 
} 
0
using System.IO; 

string result = gerneralRootPath.Replace(Path.GetFileName(gerneralRootPath), documentName); 

隨着Path.GetFileName(來自System.IO)你得到你的文件名:

銷售。 2010+ Implementation + Revised + Feb10.pdf

Res ULT是:

文件/ Z_Do​​cumentation/PDF/doc123

0

請找樣本代碼

int i = gerneralRootPath.IndexOf("/PDF/"); 

if (i >= 0) gerneralRootPath = gerneralRootPath.Substring(0,i+5); 

我希望這將幫助你....