为即将到来的考试做一些练习。有点卡在这个。
“编写一个程序,要求用户输入两个字符串,如果第二个字符串包含在第一个字符串中循环包含,则检查并打印一条消息。循环包含意味着第二个字符串正常出现在第一个字符串中,或者第二个字符串出现如此它的前缀出现在第一个字符串的末尾,而延续出现在第一个字符串的开头”。
您可以假设字符串仅包含小写字母。只允许使用字符串函数:strlen、strcpy、strcmp、strcat
例如:
字符串 A:iti sanic eday 字符串 B:sanic
是否经常发生
字符串 A: it isanice day字符串 B: dayit
这是一个循环出现。
到目前为止我做了什么:
#include <iostream>
#include <string.h>
using namespace std;
#define Max 128
int isCyclic(char* str1, char* str2);
int main()
{
char* str1 = new char[Max];
char* str2 = new char[Max];
cout << "Please enter two strings:" << endl;
cin >> str1 >> str2;
cout << isCyclic(str1, str2) << endl;
delete[] str1;
delete[] str2;
}
int isCyclic(char* str1, char* str2)
{
int s1 = strlen(str1);
int s2 = strlen(str2);
if (s1!=s2) // if string size is diffrent - they are not contained cyclic
{
return 0;
}
}
您将需要两个循环,第一个在字符串 1 上,这是我们在字符串 1 中用于比较的起点,第二个在字符串 2 上,它将以循环方式与字符串 1 匹配。如果到达字符串 1 的末尾,但字符串 2 中仍有一些字符,则从索引 0 开始循环遍历字符串 1。
#include <stdio.h>
#include <iostream>
#include <string.h>
// Should be avoided in general. Use scope resolution instead.
using namespace std;
char* isCyclic(char* s1, char* s2){
int s1_size = strlen(s1);
int s2_size = strlen(s2);
// s1 must contain s2
if(s2_size > s1_size)
return "No Occurence";
for(int i = 0; i < s1_size; i++){
int current = i;
// Boolean to track if we are currently cycling through s1
bool inCycle = false;
int j = 0;
for(; j < s2_size; j++, current++){
// character wise comparision
if(s2[j] != s1[current])
break;
if(! inCycle){
// start from first. Note that we are setting current = -1.
// as we will be incrementing it in the for loop.
if(current == s1_size - 1 && j < s2_size - 1){
current = -1;
inCycle = true;
}
}
}
if(j == s2_size){
if(inCycle)
return "cyclic";
else
return "regular";
}
}
return "No Occurence";
}
int main()
{
printf("Hello World\n");
char* s1 = "itisaniceday";
char* s2 = "dayitis";
cout<<"Occurence Type: "<<isCyclic(s1, s2)<<endl;
return 0;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句