c# - 替换逗号分隔列表的单个字段中的字符

标签 c# string

我的c#代码中有字符串

a,b,c,d,"e,f",g,h

我想用“e f”替换“e,f”,即在引号内的 ',' 应该用空格替换。

我尝试使用 string.split,但它对我不起作用。

最佳答案

好吧,我懒得考虑正则表达式方法,所以我将提供一种老式的循环方法,它会起作用:

string DoReplace(string input)
{
    bool isInner = false;//flag to detect if we are in the inner string or not
    string result = "";//result to return

    foreach(char c in input)//loop each character in the input string
    {
        if(isInner && c == ',')//if we are in an inner string and it is a comma, append space
            result += " ";
        else//otherwise append the character
            result += c;

        if(c == '"')//if we have hit an inner quote, toggle the flag
            isInner = !isInner;
    }

    return result;
}

注意:此解决方案假设只能有一层内引号,例如您不能有 "a,b,c,"d,e,"f,g",h",i, j" - 因为这简直是疯了!

关于c# - 替换逗号分隔列表的单个字段中的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21905228/

相关文章:

r - 在单词列表上拆分字符串

C++ 返回字符串

c# - SQL 连接

c# - 为什么 Rhino Mocks 在与线程一起使用时会抛出异常?

c# - XMLSerializer : <ImplementationException xmlns ='urn:epcglobal:ale:wsdl:1' > was not expected

c# - 带有数字键的动态 json 对象

c# - 按列宽自动拉伸(stretch) ListView 行

c# - MemoryStream 到 String,然后返回到 MemoryStream,而不添加任何字节(编码等)

c++ - C++ 中的字符串到 const char * 将垃圾放在末尾

javascript - 字符串的哪一部分不同? (JavaScript)