[英]Check if a string of type char * contains another string
我有一个更大的任务,其中包含此功能。 这是说明;
定义一个名为 isPartOf 的 C++ 函数,带有两个指向 C 字符串的参数指针(即 char * 类型,不是来自尚未详细声明的 C++ 数据类型 string )并返回一个布尔值。
本质上,函数应该检查第一个参数指针指向它的字符串是否是第二个参数指针指向它的字符串的一部分。
示例: isPartOf ("heart", "hypertensive heart disease") 返回真值 isPartOf ("screw", "Case Involving Wheelchair") 返回假值。
我已经学习 C 一年了,才开始学习 C++,我发现很难理解“char *”和参数的一般用法。 我花了一段时间才理解指针,现在参数让我失望了。 我已经尝试了可能所有可能的 * 和 & 迭代的代码,只是为了看看它是否可以工作,但它没有。
#include <iostream>
using namespace std;
void isPartOf(char *, char *);
int main()
{
char * Word;
char * Sentence;
cout << "Please enter a word: ";
cin >> Word;
cout << endl << "Please enter a sentence: ";
cin >> Sentence;
cout << endl;
isPartOf(Word, Sentence);
if (isPartOf(Word, Sentence))
{
cout << "It is part of it";
}
else
{
cout << "It is not part of it";
}
}
void isPartOf(char a, char b)
{
}
我在这里的两个主要问题是;
由于这是 C++,最简单的解决方案是使用string
。 您实际上无法按照您尝试的方式cin
字符数组(该代码没有按照您的想法执行),因此这也解决了您的输入问题:
std::string Word, Sentence;
cout << "Please enter a word: ";
std::getline(std::cin, Word);
cout << endl << "Please enter a sentence: ";
std::getline(std::cin, Sentence);
cout << endl;
if (isPartOf(Word, Sentence)) {
// ...
}
string
的另一个isPartOf()
是它使isPartOf()
非常简单:
bool isPartOf(const std::string& word, const std::string& sentence) {
return sentence.find(word) // this returns the index of the first instance
// word
!= std::string::npos; // which will take this value if it's not found
}
或者,它可以使用strstr
实现:
return strstr(sentence.c_str(), word.c_str());
基于@alex.b 代码,我写了以下几行。 我还考虑了禁止使用任何库函数的事实
bool isPartOf(char* w1, char* w2)
{
int i=0;
int j=0;
while(w1[i]!='\0'){
if(w1[i] == w2[j])
{
int init = i;
while (w1[i] == w2[j] && w2[j]!='\0')
{
j++;
i++;
}
if(w2[j]=='\0'){
return true;
}
j=0;
}
i++;
}
return false;
}
char* 是指向字符串中第一个字符的第一个内存地址的指针。 当您第一次声明 char* 时,它并未设置为内存地址,因此您将无法在其中存储任何数据。 因此,您需要为该 char* 分配内存,以便您可以开始在其中存储数据。 例如:
word = (char*) malloc(number_of_bits * sizeof(char));
记住 malloc 要求你包含 stdlib.h
#include <stdlib.h>
一旦您有空间开始在该 char* 中存储数据,您就可以使用 cin 读入数据。
此外,当您将指针传递给另一个函数时,您需要确保将 char* 传递给的参数也是 char* 类型
void isPartOf(char *a, char *b){
...
}
最后要确定另一个字符串是否包含子字符串,我将使用 strstr 函数
bool isPartOf(char *a, char *b){
if(std::strstr(b,a) != NULL){ //Strstr says does b contain a
return true;
}
return false;
}
试试这个:
#include <iostream>
#include <string.h>
using namespace std;
bool isPartOf(char* w1, char* w2)
{
int i=0;
int j=0;
for(i;i < strlen(w1); i++)
{
if(w1[i] == w2[j])
{
j++;
}
}
if(strlen(w2) == j)
return true;
else
return false;
}
int main()
{
char wrd1[] = "As I know there is a function in C++ string which performs substring search: string1.find(string2)";
char* W1 = wrd1;
char wrd2[] = "search";
char* W2 = wrd2;
if(isPartOf(W1,W2))
cout << "true";
else
cout << "false";
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.