简体   繁体   中英

C# insert values to string

Ok so basically I have a string that looks like this

"this is random text [this is random too] [another random text] hey ho [random bar]"

I want the output to be

"this is random text [[this is random too]] [[another random text]] hey ho [[random bar]]"

So basically find every [ and append an [ to it and same for the ]

What would be the best way to do this? Thanks.

So basically find every [ and append an [ to it and same for the ]

Sounds like:

text = text.Replace("[", "[[")
           .Replace("]", "]]");

to me... no need for a regular expression at all.

That is assuming you don't need to worry about brackets which are already doubled, of course.

This will be more efficient because the array will never have to be resized. Although the difference is so small you're probably better off using Jon Skeet's method.

public string InsertBrackets(string text)
{
    int bracketCount = 0;
    foreach (char letter in text)
        if (letter == '[' || letter == ']')
            bracketCount++;

    StringBuilder result = new StringBuilder(text.Length + bracketCount);

    for(int i = 0, j = 0; i < text.Length && j < result.Length; i++, j++)
    {
        result[j] = text[i];

        if (text[i] == '[')
            result[++j] = '[';
        else if (text[i] == ']')
            result[++j] = ']';
    }

    return result.ToString();
}

Or given you've tagged this with regex:

var foo = "this is random text [this is random too] " +
    "[another random text] hey ho [random bar]";
var regex = new Regex(@"\[(.*?)\]");
string bar = regex.Replace(foo, @"[[$1]]");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM