如何从数组中的字符串中删除尾部双引号?

时间:2016-06-07 16:41:38

标签: c# arrays string

我有一个字符串数组,其中数组中的某些字符串具有\"最后:

var splits = def.definition.Split(new string[] { @"; """ }, 
    StringSplitOptions.RemoveEmptyEntries); 

splits[0] = "good string";
splits[1] = "problem string \"";

有人可以建议我可以迭代这个数组并删除某些行中存在的\"吗?是否有可能在我已经拥有的代码之后执行此操作,以便分割?

此处参考完整代码。注意\"对于splits数组的元素[0]之后的所有内容只是一个问题:

var splits = def.definition.Split(new string[] { @"; """ }, 
    StringSplitOptions.RemoveEmptyEntries);
return new WebWordForm
{
    definition = CultureInfo.CurrentCulture.TextInfo
        .ToTitleCase(splits[0].ToLower()),
    examples = splits.Skip(1).ToList(),
    partOfSpeech = definition.partOfSpeech,
    sourceId = 1,
    synonyms = def.synonyms
};

以下是一些定义的示例数据:

def.definition = "the trait of lacking restraint or control; " +
    "freedom from inhibition or worry; \"she danced with abandon\""

def.definition = "a feeling of extreme emotional intensity; " + 
    "\"the wildness of his anger\""

def.definition = "forsake, leave behind; " + 
    "\"We abandoned the old car in the empty parking lot\""

def.definition = "stop maintaining or insisting on; " + 
    "of ideas, claims, etc.; " + 
    "\"He abandoned the thought of asking for her " + 
    "hand in marriage\"; \"Both sides have to give up " + 
    "some calims in these negociations\""

def.definition = "give up with the intent of never claiming again; " + 
    "\"Abandon your life to God\"; \"She gave up her children to her ex"

def.definition = "leave behind empty; move out of; " + 
    "\"You must vacate your office by tonight\""

3 个答案:

答案 0 :(得分:0)

您应该可以说splits = split.Select(s => s.Replace("\"", null)).ToArray()

答案 1 :(得分:0)

修改

基于您的示例数据,看起来更有效的方法是使用引号作为分隔符进行拆分:

var splits = def.definition
                .Split(new string[] { "; ", "\" }, StringSplitOptions.RemoveEmptyEntries);

然后第一个元素是定义,剩下的元素就是例子。

或者只是在"; "上拆分,引号包围的任何内容都是一个例子。

Linq用于查询,而不是更新,因此如果您想要更新计划中的项目,那么只需使用for循环:

for(int i=0; i<splits.Length; i++
{
    splits[i] = splits[i].Replace(@"/"","");
}

如果你想使用Linq项目将数组转换为 new 数组(复制时间并根据需要进行替换),那么你可以使用:

splits = splits.Select(s => .Replace(@"\"",""))
               .ToArray();

您可以使用Split

进行内联
var splits = def.definition
                .Split(new string[] { @"; """ }, StringSplitOptions.RemoveEmptyEntries); 
                .Select(s => s.Replace("\"",""));

如果你需要最终结果是一个数组,那么你可以添加ToArray(),但是制作Split数组的副本产生。对你来说这可能不是一个问题,但需要考虑。

答案 2 :(得分:0)

您可以遍历数组本身并使用TrimEnd()方法替换每个元素,或者只需使用LINQ创建投影并通过Select()方法以这种方式处理替换:

// Loop approach
for(var i = 0; i < splits.Length; i++)
{
    splits[i] = splits[i].TrimEnd('\"');
}

// LINQ projection
splits = splits.Select(s => s.TrimEnd('\"')).ToArray();

你可以see an example of this here

更高级的方案

如果您需要处理任何更有利的替换,您可以考虑通过Regex.Replace()方法使用正则表达式,但是对于简单的修剪,这应该足够了:

// Trim off any trailing quotes or spaces
splits = splits.Select(s => Regex.Replace(s,@"[\s"]","")).ToArray();