2011-06-25 75 views
-3

替换字符串我有一个存放字符串变量,让我们这样说:与字符串格式

string str = "https://stackoverflow.com/a/b/1/cdd/d.jpg"

我有字符串格式,可以这样说:

string frmt = "https://stackoverflow.com/a/b/{0}/be/" 

现在,我想用frmt替换str中的字符,类似这样的:

string newstr = str.Replace(frmt); 
//result should be: /a/b/1/be/d.jpg 

Do .net框架有类似的东西?如何轻松完成?

谢谢。

+0

所以要合并两个字符串? – Vercas

+0

否,str的格式为“/ [string1]/[string2]/[string3]/[string4]/[string5]”,string1,2,3和5保持不变,只有string4变化,知道string1和2 .. – Nir

回答

0

您可以使用String.Split来分隔段,然后更换指数之你需要的。之后,您可以使用String.Join构建备份字符串。

这里是一个快速和肮脏的例子:

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string myReplacement = "4"; 
      StringBuilder temp = new StringBuilder(); 
      string str = "https://stackoverflow.com/a/b/1/cdd/d.jpg"; 
      string[] splitArray = new string[] { "/" }; 
      string[] split = str.Split(splitArray,StringSplitOptions.RemoveEmptyEntries); 

      if (split.Length > 1) 
       split[2] = myReplacement; 

      str = "/" + string.Join("/", split);  
     } 
    } 
} 
4

使用string.Format

string.Format("https://stackoverflow.com/a/b/{0}/be/","1") 

或者是你想有一个正则表达式?

然后,你需要Regex.Replace

+0

不,你让我错了,看看我给的例子..我想用模式替换str中的部分字符串,其中一些字符我想保持原样(我不知道它们是什么,那么为{0}) – Nir

+0

然后,你需要的是使用正则表达式'Regex.Replace' – bevacqua

+1

@nir - 问题是你的例子没有多大意义。如果“/ a/b/{0}/be /”是格式字符串,那意味着最后的字符串应该是相同的,除了{0}部分应包含要替换的内容。检查你的最终字符串 - 它只是你的前两个字符串的混合。我认为你需要清理你的榜样,然后人们才能正确回答你的问题。 –

0

使用StringBuilder

string testString ="some {replace_me} text"; 
StringBuilder sb = new StringBuilder(testString); 
sb.Replace("{replace_me}", "new"); 
sb.ToString(); 

sb.ToString()将有 “一些新的文本”