Frantumn
Frantumn

Reputation: 1764

Replace brackets from a string

I have to replace all { and } brackets in a string with [ and ].

But I have one { at the very start and one } at the very end of the string that can't change.

How would I do this in C#?

Upvotes: 0

Views: 761

Answers (2)

Pieter21
Pieter21

Reputation: 1845

    [TestMethod]
    public void Replace()
    {
        string before = "{{{abc}}";
        string expect = "{[[abc]}";

        string calc = '{' + before.Substring(1, before.Length - 2).Replace('{', '[').Replace('}', ']') + '}';

        Assert.AreEqual(expect, calc);
    }

Upvotes: 0

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391456

There's probably many ways to do this, including replacing them all and replacing first/last back to original value, but here is a Regex replacement method that will replace all the braces except the first { and the last }.

You can test this in LINQPad

void Main()
{
    string input = "{ a{b}c }";

    int indexOfFirstBrace = input.IndexOf('{');
    int indexOfLastBrace = input.LastIndexOf('}');

    string output = Regex.Replace(input, "[{}]", match =>
    {
        if (match.Index == indexOfFirstBrace || match.Index == indexOfLastBrace)
            return match.Value;

        if (match.Value == "{")
            return "[";
        return "]";
    });

    output.Dump();
}

Output:

{ a[b]c }

Here's another method that would deconstruct the string into a character array, gather up all the characters and build another string, doing the replacements character by character.

string output = new string(input
    .Select((c, i) =>
        i == indexOfFirstBrace || i == indexOfLastBrace ? c
            : c == '{'                                  ? '['
            : c == '}'                                  ? ']'
                                                        : c)
    .ToArray());

Upvotes: 4

Related Questions