【问题标题】:How to make sure that two strings only have certain alphabets in c++如何确保两个字符串在c ++中只有某些字母
【发布时间】:2018-11-13 21:11:01
【问题描述】:

目的是确保用户输入的字符串 1 和字符串 2 仅包含任意顺序的字符 A、T、G 或 C。如果任一字符串包含另一个其他字符,则应显示错误。示例:

输入包含错误

字符串 #1 中的错误:aacgttcOgMa

字符串 #2 中的错误:ggataccaSat

这是我对 LCS.cpp 文件代码的尝试:

#include "LCS.h"
#include <string>

using namespace std;

bool validate(string strX, string strY)
{

string x = strX;
string y = strY;
char searchItem = 'A';
char searchItem = 'C';
char searchItem = 'G';
char searchItem = 'T';
int numOfChar = 0;
int m = strX.length();
int n = strY.length();
for (int i = 0; i < m; i++)
{
    if (x[i] == searchItem)
    {
        numOfChar++;

    }
for (int i = 0; i < n; i++)
    {
        if (y[i] == searchItem)
        {
            numOfChar++;

        }
}

}

这是我的 LCS.h 文件代码:

#pragma once
#ifndef LCS_H
#define LCS_H

#include <string>

using namespace std;

bool validate(string strX, string strY);
#endif

我的驱动文件“Driver6.cpp”有这个代码:

#include "LCS.h"
#include <iostream>
#include <string>


using namespace std;

int main()
{
string strX, strY;

cout << "String #1: ";
cin >> strX;
cout << "String #2: ";
cin >> strY;

//validate the input two strings
if (validate(strX, strY) == false)
{
    return 0;
}

int m = strX.length();
int n = strY.length();

}

【问题讨论】:

  • 您似乎正在尝试创建 4 个具有相同名称的单独变量。您需要做的就是遍历字符串并使用 if 语句检查每个字符是 A、G、T 还是 C。你不需要这些变量。
  • @NeilButterworth 你能告诉我你是如何编写一个可以查找两个不同字符串的 if 函数吗?
  • 遍历循环中的第一个字符串。然后在另一个循环中查看第二个字符串。无论如何,验证函数没有理由将两个字符串作为参数。
  • @NeilButterworth 这看起来适合第一个字符串吗? bool validate(string strX, string strY) { if (strX =! "A" || strX =! "T"|| strX =! "G", strX =! "C") { cout
  • 不,它没有。您需要一个循环,并且不需要同时验证两个字符串。

标签: c++ string dynamic char lcs


【解决方案1】:

并不是真的想这样做,但这似乎是最好的选择,而不是在 cmets 的房子周围转:

#include <string>
#include <iostream>

bool validate( const std::string & s ) {
    for ( auto c : s ) {
        if ( c != 'A' && c != 'T' && c != 'C' && c != 'G' ) {
            return false;
        }
    }
    return true;
}

int main() {
    std::string s1 = "ATGCCCG";
    std::string s2 = "ATGfooCCCG";

    if ( validate( s1 ) ) {
        std::cout << "s1 is valid\n";
    }
    else {
        std::cout << "s1 is not valid\n";
    } 
    if ( validate( s2 ) ) {
        std::cout << "s2 is valid\n";
    }
    else {
        std::cout << "s2 is not valid\n";
    } 
}

【讨论】:

  • 非常感谢。大约一个小时后,我终于明白了!
【解决方案2】:

另一种技巧:

bool validate(const std::string& s)
{
  const static std::string valid_letters("ATCGatcg");
  for (auto c: s)
  {
     std::string::size_type position = valid_letters.find_first_of(c);
     if (position == std::string::npos)
     {
        return false;
     }
  }
  return true;
}

上面的代码搜索一个包含有效字母的容器。

【讨论】:

    猜你喜欢
    • 2018-03-29
    • 1970-01-01
    • 1970-01-01
    • 2017-12-25
    • 2020-03-19
    • 2015-09-08
    • 2022-01-05
    • 2018-03-03
    • 2013-03-23
    相关资源
    最近更新 更多