我需要一些帮助才能将此代码转换为C ++ 我会很感激的。
程序必须搜索字符串的字符串insido并显示它是否已找到。
#include "iostream"
#include "string"
#include "stdlib.h"
using namespace std;
int main()
{
// Input Secuence
String Entrada = "ABCDE12345";
// Secence to search
String Secuencia = "DE12";
// Variable to store each letter and number of the secuence
Char Buscar;
//Flag to show if the secuence was found
Boolean Existe = false;
//Cicle to read all the Input Secuence
for (int i = 0; i < Entrada.Count(); i++) {
//The letter is stored
Char Letra = Entrada[i];
// This is the first letter in the secuence to search
Buscar = Secuencia[0];
//If the letter of the input secuence matchs with the first letter
//of the secuence to search, this is the base position then search
//if the word exist
if (Letra == Buscar) {
//Cicle to read all the word to search and start to compare heach letter
//of the input secuence starting from the current position.
for (inf x = 1; x z Secuencia.Count(); x++) {
// Obtaining the following letter of the input secuence
Letra = Entrada[i + x];
// Obtaining the following letter of the input secuence
Buscar = Secuencia[x];
//Compare if the letter are equal
if (letra == Buscar)
{
//If they are equal the falg change to "true"
Existe = false;
//Out of the cicle
break;
}
}
//If the word is already fin it, then leave the cicle of reading
if (Existe)
{
//End of the cicle
break;
}
}
}
//Show the input secuence
Console.WriteLine("Entrada : " + Entrada);
// SHow the output secuence
Console.WriteLine("Secuencia a buscar : " + Secuencia);
//Confirm if the word was found it
if (Existe)
{
//If exist show "found the secuence searched"
Console.WriteLine("La Encontre");
}
else {
//If do not exist show "an error message"
Console.WriteLine("No existe");
}
}
}
我是C ++的新手,我真的迷失了很多项目
提前致谢
答案 0 :(得分:1)
std::string
能够使用其成员函数.find()
搜索子字符串。
有了它,您的整个功能可以写成几行。
#include <iostream>
#include <string>
int main() {
std::string entrada = "ABCDE12345";
std::string secuencia = "DE12";
std::cout << "Entrada : " << entrada << '\n'
<< "Secuencia a buscar : " << secuencia << '\n';
if (entrada.find(secuencia) != std::string::npos) {
std::cout << "La Encontre\n";
} else {
std::cout << "No existe\n";
}
}
这里,std::string::npos
是find
返回的标记值,如果字符串不包含子序列(否则它将返回子序列开始处的字符的索引)。 / p>
如果您有权访问C ++ 17,您还可以使用std::search
来指定所使用的算法。链接引用有一个示例,其中使用Boyer-Moore算法搜索子字符串。