c#函数返回字符串中不在另一个字符串中的字母

时间:2015-04-19 15:52:54

标签: c# string

我们说我有两个字符串:main_word: 'abcdefa'check_word: 'abcd'

我知道check_word中的字母都在main_word中。

我必须编写一个函数,在使用所有字母组成check_word后,将main_word的其余部分返回给我。在上面的示例中,函数将返回字符串efa

这是我的代码:

private static string getResidue(string, main_word, string check_word)
{
    string result = "";
    bool isFound;

    foreach (char c in main_word)
    {
        isFound = false;
        for(int i = 0; i < check_word.Length; ++i)
        {
            if (c == check_word[i])
            {
                //check_word[i] = 'x'; mark as used (this doesn't work) 
                isFound = true;
                break;
            }
        }
        if (!isFound) result += c;
    }

    return result;
}

问题是这个版本不支持重复的字母。我评论了可以解决我的问题的版本,但不幸的是,c#不允许该行,因为property of indexer cannot be assigned to - it is read only。 任何想法如何使这个功能按预期工作?

3 个答案:

答案 0 :(得分:1)

没错,您无法删除或替换string中的字符,因为在C#中string 不可变

解决此问题的一种方法是维护可变字符集合。例如,如果您将字符串中的所有字符复制到另一个集合(例如,List<char>),那么您就可以从中删除项目。

您可以使用Linq方法check_list.ToList()string转换为List<char>

答案 1 :(得分:0)

因为我显然无法阅读或理解英语中最简单的东西,如字母,这里有更新;

var a = "abcdefa";
var b = "abcd";

var c = b.ToCharArray().ToList();
var res = a.ToCharArray().Where(x => !c.Remove(x));

这会产生结果&#39; e&#39; f&#39;和&#39; a&#39;无论你怎么扭曲并转动清单,它都会起作用。

答案 2 :(得分:0)

这可能适合你:

public string getResidue(string main_word, string check_word)
{
    foreach (char c in check_word)
    {
        int idx = main_word.IndexOf(c);
        if (idx > -1)
        {
            main_word = main_word.Remove(idx, 1);
        }
    }
    return main_word;
}