从字符串中读取(可能的数组用法?C++

Read from string (possible array usage?) C++

本文关键字:数组 用法 C++ 字符串 读取      更新时间:2023-10-16

我试图在这里编写alil函数,它基本上是从字符串中读取的。它每三个字符读取一次,并使用前提条件(if 语句(对其进行计算。如果满足条件,它将用新的三个字母替换这三个字母。然后它将输出新字符串。

我尝试编写代码,但似乎无法获得正确的逻辑。 程序运行,但不打印出任何内容。不要介意函数名称和不准确之处。我只是在做一个示例函数来测试这一点。

string amino_acids(string line)
{
    string acid;
    string acids;
    string newline;
    for( int i= 0; i < line.length(); i++)
    {
        acid = line[i];
    }
    for (int i = 0; i < 3; i++)
    {
        acids = acid[i];
        if(acids == "GUU")
        {
            acids = "ZAP";  
        }
        newline = acids;
    }
    cout << "Acids: " <<newline <<endl;
    return newline;
}
for( int i= 0; i < line.length(); i++)
    acid = line[i];

假设行包含"abcd",这个循环将要做:

acid = 'a';
acid = 'b';
acid = 'c';
acid = 'd';

只有最后一项任务具有持久的影响。 如果你需要实际将三个字符从行中获取到酸中 - 您可能希望使用+=将字符添加到acid中,而不是=。 但是,如果你像这样遍历所有行,你最终会做acid = line;。 我假设你想要更像acid = line.substr(0, 3)的东西?

for (int i = 0; i < 3; i++)
{
     acids = acid[i];

这将崩溃。 acid 绝对是单个字符串,您将在第二次和第三次迭代中索引acid[1]acid[2]。 当你在学习C++时,你可能应该使用.at(i)当你尝试使用无效索引时会抛出异常 - 你可以捕获异常,至少有一些问题的迹象。 照原样,这是未定义的行为。

要使用,您需要一个try/catch块...基本形式为:

int main()
try
{
    ...your code in here...
    some_string.at(i);
}
catch (const std::exception& e)
{
    std::cerr << "caught exception: " << e.what() << 'n';
}

更一般地说,尝试在整个代码中放置一些std::cout语句,以便您知道变量实际具有哪些值...你很容易发现它们不是你所期望的。 或者,使用交互式调试器并观察每个语句执行的影响。

使用 [] 运算符索引std::string会产生一个char,为此恰好有一个字符串的重载operator=

即使您按照我相信您的意图循环(正如对问题的评论所提到的,您可能不是(,因为酸(取单个字符的值(永远不会等于您正在比较它的三个字符串。 因此,不会执行任何替换。

要执行所需的操作,请尝试如下操作:

for (int i = 0; i + 3 < line.length(); i += 3) // counting by 3 until end of line
{
    if (line.substr(i, 3) == "GUU")            // if the substring matches
    {
        line.assign("ZAP", i, 3);              // overwrite it with new substring
    }
}
return line;

从你的描述中读到,你想要这样的东西

//note below does not compile, its just psuedo-code
string amino_acid(const string& sequence){
  string result = sequence; //make copy of original sequence
  For i = 0 to sequence.length - 3 
    string next3Seq = sequence(i,3); //grab next 3 character from current index
    If next3Seq == 'GUU' //if the next next three sequence is 'GUU'
      then result.replace(i,3,'ZAP'); //replace 'GUU' with 'ZAP'
    EndIf
  EndFor
  return result;   
}

您可以将其用作编码的开始。祝你好运。

根据我对你问题的理解。我写了一些代码。请看下面

string acids;
string newLine;
int limit=1;
for(int i=0;i<line.length();i++)
{
    acids=acids+line[i];
    if(limit==3)//Every 3 characters
    {
      if(acids == "GUU")
        {
            acids = "ZAP";  
        }       
        limit=1;
        acids=""
        newline=newline+acids;
    }
limit++;
    return newline;
}