关于C#:无法正确地从一个字符到另一个字符消除一个字符串


Cannot properly eliminate string one from another character by character

在这里,函数(sub)将两个字符串作为输入,遍历两个字符串,我试图找出string1与string2相比是否有任何匹配项。如果有的话,将string1的那个字符替换为NULL字符。现在,此方法适用于非重复字符。但是,如果string1具有多个匹配一次的字符,则全部替换为NULL字符,而我只需要替换一次即可。例如,如果string1和string2为122和2,则消除后我需要1 2,其中我现在得到一个1。

1
2
3
4
5
6
7
8
9
void sub (string str1, string str2){
    int i,j,k;
    for(i=0; i<=str2.size() ; i++){  
        for(j=0; j<=str1.size() ; j++ ){
            if( str2[i] == str1[j] )
                str1[j] = NULL;
        }
    }
    cout<<str1;

如果str1 = 122和str2 = 2

,则预期结果是1 2而不是1


您正在使事情变得更加困难。 string库提供了两个函数,这些函数可以在一次调用中完全满足您的需求。

成员函数std :: basic_string :: find_first_of将定位string1string2中字符的第一个匹配项,并返回找到该字符的位置。

std :: basic_string :: erase函数可以删除string1中从该位置开始的所有字符。

您的sub函数将减少为:

1
2
3
4
void sub (std::string& s1, const std::string& s2)
{
    s1.erase (s1.find_first_of (s2));
}

使用给定字符串的简短示例为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <string>

void sub (std::string& s1, const std::string& s2)
{
    s1.erase (s1.find_first_of (s2));
}

int main (void) {

    std::string s1 ("122"), s2 ("2");

    sub (s1, s2);

    std::cout <<"s1:" << s1 <<"\
s2:"
<< s2 << '\
'
;
}

使用/输出示例

1
2
3
$ ./bin/sub1at2
s1: 1
s2: 2

仔细检查一下,如果还有其他问题,请通知我。


不能通过将其设置为NULL从字符串中删除字符。字符串的长度将保持不变。但是,模拟删除重复项的一种方法是返回与返回条件匹配的新字符串。

首先遍历第二个字符串,然后使用哈希表将s2中的每个字符映射为true。然后遍历s1,仅当哈希表中的字符映射为false时,才将当前字符添加到新字符串中。在这种情况下,将字符重新映射为false可以确保将字符数(除一个以外的所有字符)写入结果字符串。

1
2
3
4
5
6
7
8
9
10
string remove_first_duplicates(string s1, string s2) {
  unordered_map<char, bool> m;
  string result;
  for (char i : s2) m[i] = true;
  for (char i : s1) {
    if (!m[i]) result += i;
    m[i] = false;
  }
  return result;
}

  • 即使\\0是空字符,

    NULL也不是字符常量。它是一个空指针常量的宏,出于历史原因,通常将其定义为0,尽管它可能是nullptr或任何其他空指针常量。

  • 将字符归零并不能阻止它们成为字符串的一部分。为此,您必须移动其余的并调整长度。

  • 如果只想执行一次,则在第一个匹配项上,然后使用return保留该功能。

  • 请考虑将其分为两个功能:一个用于查找匹配项,一个调用该函数并使用结果删除第一个匹配项。


  • 据我所知,您想从str1中删除一个与str2中的匹配项相对应的字符。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    void sub(string str1, string str2)
    {
        int i = 0, j = 0;
        while (j < str2.size())
        {
            if (str1[i] == str2[j])
            {
                str1[i] = NULL;  // could use str1.erase(i,1)
                i = 0;
                j += 1;
                continue;
            }
            else
                i += 1;
            if (i == str1.size() - 1)
            {
                i = 0;
                j += 1;
            }
        }
        cout<<str1<<endl;
    }

    这将产生您想要的输出。但这会在str1中产生NULL char,更好的选择是使用std::string中的erase功能。