2016-06-13 132 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); 

我希望这将帮助你....