wozzarvl
wozzarvl

Reputation: 364

Replace commas in string C#

I have a string like this:

select name,lastname,email from contacts

I want to replace the commas for +"|"+ and get something like this

select name+"|"+lastname+"|"+email from contacts

thats easy with string.Replace(",",+"|"+);

but the problem is when i face a string like this:

select name,lastname,isnull(email,0) from contacts

How i cant detect to avoid the commas inside the isnull()? with the replace i get a string like this

select name+"|"+lastname+"|"+isnull(email+"|"+0) from contacts

and thats wrong!

thanks .

Upvotes: 0

Views: 1867

Answers (2)

PiotrK
PiotrK

Reputation: 1552

Try this:

public static string ReplaceTopLevelCommas(string query)
{
    var newQuery = new StringBuilder();
    var level = 0;

    foreach (var c in query)
    {
        if (c == ',')
        {
            if (level == 0)
            {
                newQuery.Append("+\"|\"+");
            }
            else
            {
                newQuery.Append(c);
            }
        }
        else
        {
            if (c == '(')
            {
                level++;
            }
            else if (c == ')')
            {
                level--;
            }

            newQuery.Append(c);
        }
    }

    return newQuery.ToString();
}

It replaces commas only if they're not inside any parentheses. So it will also work for multiple levels of nesting.

Working example: http://ideone.com/TGPRe2

Upvotes: 3

sweerpotato
sweerpotato

Reputation: 480

Simply write your own method:

private static string replace_commas(String str_)
{
    StringBuilder str = new System.Text.StringBuilder(str_);

    bool replace = true;

    for(int i = 0; i != str.Length; ++i)
    {
        if(str[i] == ',' && replace)
            str[i] = '|';

        if(str[i] == '(')
        {
            replace = false;
            continue;
        }

        if(str[i] == ')' && !replace)
            replace = true;
    }

    return str.ToString();
}

You fill in the blanks! :-)

Upvotes: 2

Related Questions