0

我有一个字符串

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

我想把这个字符串变成这个

1,1,2,2

我正在使用替换功能

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

但它不会返回预期的结果。请帮忙。

4

5 回答 5

5

您还没有删除双引号。使用以下内容:

obj.str = obj.str.Replace("[","").Replace("]","").Replace("\\","").Replace("\"", "");
于 2013-09-25T08:56:20.147 回答
2

如果字符串或排除字符列表很长,这是一种优化的方法:

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();
    }
}

以这种方式使用它:

str = str.RemoveAll('"', '[', ']', '\\'); 
// or use a string as "remove-array":
string removeChars = "\"{[]\\";
str = str.RemoveAll(removeChars.ToCharArray());
于 2013-09-25T09:48:15.443 回答
1

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('"', '[', ']', '\\');
于 2013-09-25T09:08:37.287 回答
1

您应该执行以下操作:

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

string.Replace方法不会就地替换字符串内容。这意味着如果您有字符串 test = "12345" 并执行

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

测试字符串仍然是"12345". Replace 不会更改字符串本身,而是使用替换的内容创建新字符串。所以你需要将这个新字符串分配给一个新的或相同的变量

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

现在,changedTest将包含"11345".

您的代码的另一个注意事项是您的字符串中实际上没有 \ 字符。它只是为了转义引号字符而显示。如果您想了解更多关于此的信息,请阅读 MSDN 关于字符串文字的文章。

于 2013-09-25T08:59:20.433 回答
0

仅使用此正则表达式捕获数字[0-9]+,然后连接匹配项:

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);
于 2013-09-25T09:00:54.583 回答