开发者

Replace string with string format

I have a variable that开发者_Go百科 holds string, lets say like this:

string str = "/a/b/1/cdd/d.jpg"

And I have string format, lets say like this:

string frmt = "/a/b/{0}/be/"

Now, I want to use frmt to replace chars in str, something like that:

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

Does the .net framework has something like that? How can it be done easily?

Thanks.


Use string.Format

string.Format("/a/b/{0}/be/","1")

Or is it a regular expression you want?

Then you need Regex.Replace


Use StringBuilder

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

sb.ToString() will have "some new text"


You can use String.Split to separate your sections, then replace the indice that you need. After that you can build back up your string by using a String.Join .

Here is a quick and dirty example:

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string myReplacement = "4";
            StringBuilder temp = new StringBuilder();
            string str = "/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);     
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜