从字符串中读取(可能的数组用法?C++
Read from string (possible array usage?) C++
我试图在这里编写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;
}
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- 访问基类型数组成员(Int-to-type习惯用法)
- 如何制作具有动态大小的数组?动态数组的一般用法(可能还有指针)
- 指针数组用法
- C++析构函数删除包含动态数组作为数据成员的对象时的用法
- 从字符串中读取(可能的数组用法?C++
- 在类中声明2d数组及其后面的用法
- r语言 - 用NumericVector填充c++数组的更好的习惯用法