字符串删除:编写一个程序,提示用户输入两个字符串,将第二个字符串中包含的字符从第一个字符串中删除。要求:编写一个字符删除函数 char *remove(char *str, char *chars),用 new 分配新的字符数组(大小为 str 的长度 +1),将 chars 中包含的字符从 str 中删除后存入该字符数组,并返回该字符数组。在主函数中调用该函数输出结果,并用 delete 释放分配的字符数组。必须用指针方式逐个访问字符数组元素,不得使用字符串库函数。
例如输入:fjejfpifhjg933pakpj ajf3
输出:epihg9pkp
<iostream>
using namespace std;
char* remove(char* str, char* chars) {
char* n1 = str;//用来记录str的长度
char* n2 = chars;//用来记录chars的长度
int Lenstr = 0;
int Lenchars = 0;
while (*n1 != '\0') {
*n1++;
Lenstr++;
}
while (*n2 != '\0') {
*n2++;
Lenchars++;
}
char* newstr = new char[Lenstr + 1];
char* newstr1 = newstr; //用于记录newstr的首地址
for (int i = 0; i < Lenstr; i++) {
bool flag = true; //判断str中是否含有chars的字符
for (int j = 0; j < Lenchars; j++) {
if (str[i] == chars[j]) { //如果有,将flag改为false,并结束循环
flag = false;
break;
}
}
if (flag == true) {
*newstr = str[i]; //将newstr指向需要储存的str
newstr++; //newstr向后移动
}
}
*newstr = '\0';
return newstr1;
}
int main() {
char str[20];
char chars[20];
cin >> str >> chars;
char* newstr = remove(str, chars);
cout << newstr;
delete[] newstr;
}
在这道题中我们使用了动态内存的分配,实际上可以不用两个动态内存分配,只需要记录下newstr的长度,并在输出时采用循环来输出数据。
值得一提的是,new出来的newstr是一个指针,*newstr指的是指针指向的当前字符