交叉和两个字符串的并集

use*_*er7 3 c++

我必须消除字符串1中出现的字符串2,并找到两个字符串的交集.

这是我尝试过的:

#include "stdafx.h"
#include "stdio.h"
#include "conio.h"
#include "string.h"

class operation
{
public:
    char string1[100];
    char string2[50];


    operation(){};
    operation(char a[100], char b[50]);
    operation operator+(operation);
    operation operator-(operation);
    operation operator*(operation);
};

operation::operation(char a[100], char b[50])
{
    strcpy(string1, a);
    strcpy(string2, b);
}

operation operation::operator +(operation param)
{
    operation temp;
    strcpy(param.string1, temp.string1);
    strcpy(param.string2, temp.string2);
    strcat(temp.string1, temp.string2);
    return (temp);
}

operation operation::operator -(operation param)
{
    operation temp;
    strcpy(param.string1, temp.string1);
    strcpy(param.string2, temp.string2) ;
    for (int i = 0; i<strlen(temp.string2); i++)
    {
        temp.string1.erase(i, 1);
    }
    return (temp);
}

operation operation::operator *(operation param)
{
    operation temp;
    strcpy(param.string1, temp.string1);
    strcpy(param.string2, temp.string2);
    char result[50];
    for(int i = 0; i<strlen(temp.string2); i++)
    {
        if( temp.string1.find( temp.string2[i] ) != string::npos )
            result = result + temp.string2[i];
    }

    return (temp);

}
Run Code Online (Sandbox Code Playgroud)

我收到了编译器错误,我也不确定我在尝试是否正确.

错误如下:

C2228: left of .erase must have class/struct/union
C2228: left of .find must have class/struct/union
Run Code Online (Sandbox Code Playgroud)

Joh*_*web 7

令人高兴的是,在C++中,设置差异,交集联合算法已经在标准库中实现.这些可以应用于任何容器类的字符串.

这是一个演示(您可以使用简单的char数组执行此操作,但我的目的是std::string为了清晰):

#include <string>
#include <algorithm>
#include <iostream>

int main()
{
    std::string string1 = "kanu";
    std::string string2 = "charu";
    std::string string_difference, string_intersection, string_union;

    std::sort(string1.begin(), string1.end());
    std::sort(string2.begin(), string2.end());

    std::set_difference(string1.begin(), string1.end(), string2.begin(), string2.end(), std::back_inserter(string_difference));
    std::cout << "In string1 but not string2: " << string_difference << std::endl;

    std::set_intersection(string1.begin(), string1.end(), string2.begin(), string2.end(), std::back_inserter(string_intersection));
    std::cout << "string1 intersect string2: " << string_intersection << std::endl;

    std::set_union(string1.begin(), string1.end(), string2.begin(), string2.end(), std::back_inserter(string_union));
    std::cout << "string1 union string2: " << string_union << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

运行!

你如何在operation课堂上实现这一点是一个练习.


pau*_*sm4 0

  1. 这是 C++(不是 C:C 没有运算符重载)

  2. 您需要向我们展示您的类定义,然后我们才能帮助识别编译错误。

  3. 如果您没有“运算符”的类定义,那么仅此一点就可以解释错误:)

  4. 如果您使用 C++,您可能应该使用标准 C++“字符串”(而不是 C“char []”数组)。使用“字符串”也会影响您的实现代码。

  5. 问:这不会是一项家庭作业,不是吗?如果是这样,请在您的标签中添加“作业”。

提前感谢.. PSM