【发布时间】:2019-03-12 18:43:44
【问题描述】:
我需要从包含两个字符串的常用词的函数中返回一个字符串(假设只有一个常用词)。
我可以使用函数strcmp、strlen、strcat 和strcpy。
当字符串中的第一个单词相同时,我进行了管理,但如果在此之后,它就不起作用了。
不起作用的示例:
str1[] = {"Hello world"}; //string 1
str2[] = {"Thanks you world"}; // string 2
Example that work:
char str1[] = {"Hello world"}; //string 1
char str2[] = {"Hello Danny"}; // string 2
这是我的代码:
#include <iostream>
using namespace std;
# include <string.h>
char * Strcom(char str1[], char str2[]); //declare function
int main()
{
char str1[] = { "Hello world" }; //string 1
char str2[] = { "Thanks you world" }; // string 2
Strcom(str1, str2);
}
char * Strcom(char str1[], char str2[])
{
char temp[10];
int i = 0, z = 0;
while (i <= strlen(str1))//run over str1, copying word in the next while loop
{
int k = 0;
bool check = 0;
while ((z < strlen(str2)) && (k < strlen(temp)))//check that I withing the lenght...
{
char temp[10] = { 0 };
while ((str1[i] != ' ')&&(i<10))//copy one word to temp from str1
{
temp[i] = str1[i];
i++;
}
if (i != strlen(temp))
{
temp[i] = '\0';
}
else
temp[i-1] = '\0';
i++;//to jump over ' '
while (str2[z] != ' ') //check if its the same world (temp and str2)
{
if (temp[k] == str2[z])
{
k++, z++;
check = 1;
}
else
{
check = 0;
break;
}
}
if (((str2[z] == ' ') || (str2[z] == '\0')) && (check == 1))//its the same word
{
temp[k] = '\0';//to be able to print it
cout <<"my word is: " <<temp<< endl;
return temp;
}
z += 1;
k = 10;//to go to the outer while loop
}
i++;
}
}
【问题讨论】:
-
如果只有一个常用词而且你已经找到了,你为什么会觉得卡住了?
-
对你的导师任意的功能限制太糟糕了。
std::istringstream和std::unordered_set<std:string>带有一个迭代器范围构造和一个单遍循环将使它变成大约六行代码。具有讽刺意味的是,他们让您使用大多数 C++ 工程师在日常使用中避免使用的一组函数。忍住告诉他们你是否想要一门 C 语言课程的冲动,你会报名参加的。 -
@Begginer 无意冒犯,但这对他们来说是愚蠢的。这两种语言共享一个子集语法这一事实并不是这样做的理由。每一个本身就足够难了,并且为每个使用标准库的通用系统会迅速分散任何语法共性。 C 程序员会做他们想做的事; C++ 程序员会按照我的描述去做。显然,它们是非常、非常不同的东西。并不意味着你不能在 C++ 中做前者(语言和库毕竟支持它),但如果你有 C++ 标准库供你使用,你真的不会。
-
很好,您添加了示例,但究竟是什么“不起作用”?非工作示例的输出是什么?
-
@Caleth 我无意冒犯 OP。另一方面,课程的设计者应该受到鞭笞。