string的输出出现问题

#题目要求删除字符串中的特定字符,为什么如下代码输出时只输出string数组每个元素的最后一个字符
#因为还要对字符串进行其他操作,所以要用本次操作后的字符串替换原本字符串

#include 
#include <string>
using namespace std;
void Delete(string str[], char a,int n) {
    for (int i = 0; i < n; i++) {
        string str_ = {0};
        for (int j = 0; j < str[i].length(); j++) {
            if (str[i][j] != a) {
                int x=0;
                str_[x]=str[i][j];
                x++;
            }
        }
         str[i]=str_;
    }
}
int main() {
    int n;
    cin >> n;
    char a;
    cin >> a;
    string str[1000];
    for (int i = 0; i < n; i++) {
        cin >> str[i];
    }
    for (int j = 0; j < n; j++) {
        Delete(str, a, n);
        cout << str[j] << endl;
    }
    return 0;
}

##输入:
3 a
nan
kan
lok
n
##输出:
n
n
k
##期望输出:
nn
kn
lok

该回答引用ChatGPT

在给定的代码中,每次调用Delete函数时,只对一个字符串进行处理,处理后的结果存储在局部变量str_中。而在处理完该字符串后,没有将处理后的结果赋值给原来的字符串str[i],导致原来的字符串内容并没有被改变,而是保持不变。

因此,当在主函数中循环输出每个字符串时,输出的都是原来的字符串(没有改变),而不是处理后的字符串。

为了实现预期的输出,应该将处理后的字符串赋值给原来的字符串,即将以下代码:


str_[x]=str[i][j];
x++;

修改为:

str_ += str[i][j];

这样,在处理完一个字符串后,原来的字符串将会被修改,从而实现预期的输出。

主要应该是因为第6行的初始化sting为{0},指定了string的长度为一个字符,然后后面的下标变量每次都初始化为0了,每次也都是存入不等于指定字符的字符只存入了sting的第一个字符位置,所以打印的结果也只有一个字符;

可以在string初始化的长度设置长点,然后把下标变量x提到第7行第二个for 循环之前即可,另外删除函数Delete()只需调用一次,可以把它第26行之前。

修改如下:

参考链接:


https://blog.csdn.net/weixin_44143702/article/details/108626682

https://blog.csdn.net/csdn_zhangchunfeng/article/details/111368130

https://zhidao.baidu.com/question/579497704.html

#include <iostream>
#include <string>
using namespace std;
void Delete(string str[], char a,int n) {
    for (int i = 0; i < n; i++) {
        // https://www.likecs.com/show-204512968.html
        // https://blog.csdn.net/weixin_44143702/article/details/108626682
        // https://blog.csdn.net/csdn_zhangchunfeng/article/details/111368130
        string str_  = {0,0,0,0,0,0,0,0,0}; // 初始化string 
        
          int x=0;  //下标变量,在每一行遍历之前初始化为0 
    //   cout<<"str_.length="<<str_.length()<<endl;
    
        for (int j = 0; j < str[i].length(); j++) {
            if (str[i][j] != a) {
                 
               // https://zhidao.baidu.com/question/579497704.html 
                str_[x]=str[i][j];
               // str_+=str[i][j];
              // cout<<"x="<<x<<",str_["<<x<<"]="<<str_[x]<<",str_.length()="<<str_.length()<<endl; 
               x++;
            }
        }
      //  str_[x]='\0'; 
    //    cout<<"end,str_="<<str_<<",str_.length()="<<str_.length()<<endl;
         str[i]=str_;
    }
}
int main() {
    int n;
    cin >> n;
    char a;
    cin >> a;
    string str[1000];
    for (int i = 0; i < n; i++) {
        cin >> str[i];
    }
    Delete(str, a, n);
    for (int j = 0; j < n; j++) {
        
        cout << str[j] << endl;
    }
    return 0;
}
 

img