我的程序正在从字符串中删除一个字符,如何避免这种情况

My program is deleting a character from a string, how to avoid that?

本文关键字:字符 一个 何避免 情况 程序 字符串 删除 我的      更新时间:2023-10-16

我有这个程序,它应该找到一个3个字符的字符串,把"abc"说成一个更长的字符串,说"aabccbd",然后用另一个字符(说'd')替换成原始字符串的巧合。所以。给定这些字符串,结果将是:

  1. aabcabcd
  2. adabcd <<-- another iteration
  3. addd <<-- Final result

和我已经写了一些代码行,我相信解决了替换给定序列的问题(仍然没有编程替换字符)。但问题是,当我用给定的字符替换序列时,在序列被删除之前的字符。例子:

  1. aabcabcd
  2. dabcd <<-- Incorrect

可能出什么事了?请检查我的代码。序列从.txt文件中读取,格式如下:

a b c d <-序列和交换字符。(序列总是3个字符长)abcdefakxoqp333 <-我应该在其中搜索序列的完整字符串。

Code:
#include<stdio.h>
#include<iostream>
#include<stdlib.h>
#include<string.h>
using namespace std;
char* gen = new char[3];
char simp;
char dna[10001];
int main() {
    int len;
    //Reading file and assigning values.
    FILE *input = fopen("input.txt","rt");
    fscanf(input,"%c %c %c %c",&gen[0],&gen[1],&gen[2],&simp);
    fscanf(input,"%s",&dna);
    fclose(input);
    len = strlen(dna);
    //In this part dna has the 2nd line of input.txt
    for(int i=0;i<len;i++){
        cout << dna[i];
    }
    cout << endl;
    //Searching for coincidences.
    int dnaLen = len; //dna Lenght, this one will change over time.
    bool found=false;
    int index=0; //Index will be reseted as well when we make a change!!
    while(index<dnaLen-2) {
            cout << "Entering WHILE with index=" << index << "n";
            cout << "Examining: " << dna[index] << dna[index+1] << dna[index+2] << endl;
        if(dna[index]=gen[0] && dna[index+1]==gen[1] && dna[index+2]==gen[2]){
            //Replace dna[index] for simp AND displace the dna array
            dna[index]=simp;
            for(int i=0;i<dnaLen;i++){
                cout << dna[i];
            }
            cout << endl;
            index =0;
            dnaLen=dnaLen-2;
        }
        index++;
    }
    return 0;
}

我知道我可以尝试使用正则表达式,问题是我在c++ 11的使用上受到了限制。我也知道我可以使用string::replace,但这段代码有什么问题?谢谢你!

这不是比较,而是赋值,将=替换为==

if(dna[index]=gen[0]...
相关文章: