2

Hi all a have a program working but return string like ")Hi(" it should be "(Hi)" so i need to replace '(' with ')' and replace ')' with '(' it sounds easy

s.Replace('(',')').Replace(')','(')

the trick is that after the first replace the string change from ")Hi(" to "(Hi(" after the second the replace will change both characters back the final will become ")Hi)" Help Please

2
  • What if you have "(foo)Hi(bar)"? It should become ")foo(Hi)bar("? Commented May 13, 2017 at 9:14
  • no it will be (foo(Hi(bar( Commented May 13, 2017 at 9:18

5 Answers 5

2

You could also use a regex replacement.

s = System.Text.RegularExpressions.Regex.Replace(s, @"[)](\w+)[(]", "($1)");
Sign up to request clarification or add additional context in comments.

Comments

0

You cannot use Replace because it works its replacement operation on the whole string, not char by char.

A simple brute force solution could be this one

void Main()
{
    // A dictionary where every key points to its replacement char
    Dictionary<char, char> replacements = new Dictionary<char, char>()
    {
        {'(', ')'},
        {')', '('},
    };

    string source = ")Hi(";

    StringBuilder sb = new StringBuilder();
    foreach (char c in source)
    {
        char replacement = c;
        if(replacements.ContainsKey(c))
            replacement = replacements[c];
        sb.Append(replacement,1);

    }
    Console.WriteLine(sb.ToString());
}

You can transform this in an extension method adding to a static class

public static class StringExtensions
{
    public static string ProgressiveReplace(this string source, Dictionary<char, char> replacements)
    {
        StringBuilder sb = new StringBuilder();
        foreach (char c in source)
        {
            char replacement = c;
            if (replacements.ContainsKey(c))
                replacement = replacements[c];
            sb.Append(replacement, 1);
        }
        return sb.ToString();
    }
}

and call it from your code with

Dictionary<char, char> replacements = new Dictionary<char, char>() 
{{'(', ')'},{')', '('}};
s = s.ProgressiveReplace(replacements);

4 Comments

thank you it worked but is there a way where i do it without looping the source string i'm working with articals and books looping will be bad
Somewhere someone should loop.
sounds like it will be a pretty big string, so I would recommend new StringBuilder(source.Length);
Yes that could be done but at the moment I have no clue on the actual length of the string
0
var s = ")Hi(";            

var sb = new StringBuilder();

foreach (var c in s)
    if (c == ')')
        sb.Append('(');
    else if (c == '(')
        sb.Append(')');
    else
        sb.Append(c);

s = sb.ToString();

Comments

0

Method 1) Use the following:

var requiredString = string.Join(string.Empty, str.Select(x=>{if (x == '(') x = ')';  else if (x == ')') x = '('; return x;}));

Method 2) Or you can Use following Extension Method:

public static class StringExtensions
{
    public static string ReplaceMultiple(this string source, Dictionary<char, char> replacements)
    {
        return string.Join(string.Empty , source.Select(x=>Replace(x,replacements)));
    }

    private static char Replace(char arg, Dictionary<char, char> replacements)
    {
        if(replacements.ContainsKey(arg))
            arg = replacements[arg];
        return arg;
    }
}

This method can be used as follows:

        var rep = new Dictionary<char, char> 
        { 
            { ')', '(' }, 
            { '(', ')' }, 
            // { '#', '*' }, 
            // { '*', '#' } 
        };


        var c = str.ReplaceMultiple(rep);

1 Comment

var s = string.Concat(")Hi(".Select(c => c == '(' ? ')' : c == ')' ? '(' : c)); but it will also be slow with big strings
0

Regex.Replace lets you process each Match (needs using System.Text.RegularExpressions;) :

string result = Regex.Replace(")Hi(", @"\(|\)", m => m.Value == "(" ? ")" : "(");

Alternative can be replacing one of the characters with something else:

string result = ")Hi(".Replace('(', '\0').Replace(')', '(').Replace('\0', ')');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.