简体   繁体   中英

How to remove " [ ] \ from string

I have a string

"[\"1,1\",\"2,2\"]"

and I want to turn this string onto this

1,1,2,2

I am using Replace function for that like

obj.str.Replace("[","").Replace("]","").Replace("\\","");

But it does not return the expected result. Please help.

You haven't removed the double quotes. Use the following:

obj.str = obj.str.Replace("[","").Replace("]","").Replace("\\","").Replace("\"", "");

Here is an optimized approach in case the string or the list of exclude-characters is long:

public static class StringExtensions
{
    public static String RemoveAll(this string input, params Char[] charactersToRemove)
    {
        if(string.IsNullOrEmpty(input) || (charactersToRemove==null || charactersToRemove.Length==0))
            return input;

        var exclude = new HashSet<Char>(charactersToRemove); // removes duplicates and has constant lookup time
        var sb = new StringBuilder(input.Length);
        foreach (Char c in input)
        {
            if (!exclude.Contains(c))
                sb.Append(c);
        }
        return sb.ToString();
    }
}

Use it in this way:

str = str.RemoveAll('"', '[', ']', '\\'); 
// or use a string as "remove-array":
string removeChars = "\"{[]\\";
str = str.RemoveAll(removeChars.ToCharArray());

You should do following:

obj.str = obj.str.Replace("[","").Replace("]","").Replace("\"","");

string.Replace method does not replace string content in place. This means that if you have string test = "12345" and do

test.Replace("2", "1");

test string will still be "12345" . Replace doesn't change string itself, but creates new string with replaced content. So you need to assign this new string to a new or same variable

changedTest = test.Replace("2", "1");

Now, changedTest will containt "11345" .

Another note on your code is that you don't actually have \\ character in your string. It's only displayed in order to escape quote character. If you want to know more about this, please read MSDN article on string literals.

how about

var exclusions = new HashSet<char>(new[] { '"', '[', ']', '\\' });
return new string(obj.str.Where(c => !exclusions.Contains(c)).ToArray());

To do it all in one sweep.

As Tim Schmelter writes, if you wanted to do it often, especially with large exclusion sets over long strings, you could make an extension like this.

public static string Strip(
        this string  source,
        params char[] exclusions)
{
    if (!exclusions.Any())
    {
        return source;
    }

    var mask = new HashSet<char>(exclusions);
    var result = new StringBuilder(source.Length);
    foreach (var c in source.Where(c => !mask.Contains(c)))
    {
        result.Append(c);
    }

    return result.ToString();
}

so you could do,

var result = "[\"1,1\",\"2,2\"]".Strip('"', '[', ']', '\\');

Capture the numbers only with this regular expression [0-9]+ and then concatenate the matches:

var input = "[\"1,1\",\"2,2\"]";
var regex = new Regex("[0-9]+");
var matches = regex.Matches(input).Cast<Match>().Select(m => m.Value);
var result = string.Join(",", matches);

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