1.題目
判斷一個字符串是否爲另外一個字符串旋轉之後的字符串。
例如:給定s1 = AABCD和s2 = BCDAA,返回1,給定s1=abcd和s2=ACBD,返回0.
2.程序代碼
方法一:
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <Windows.h>
#include <string.h>
int judge_char(const char arr1[7], char arr2[7], int sz)//定義函數,達到題目要求
{
int i = 0;
int j = 0;//定義參數,控制循環次數
char mid = 0;//定義參數,作爲中間量
if (strcmp(arr1, arr2) == 0)//strcmp是比較兩字符串內容的函數
//相等返回0,左邊大返回正數,右邊大返回負數
{
return 1;
}
while (j < sz)//循環次數不能超過字符串長度
{
i = 0;//每次循環都要給i初始化
mid = arr2[0];
while (i < sz - 1)
{
arr2[i] = arr2[i + 1];
i++;
}
arr2[sz - 1] = mid;//把元素整體向左移動,第一個元素放到最後
if (strcmp(arr1, arr2) == 0)
{
return 1;
}
j++;
}
return 0;
}
int main()
{
char s1[] = "ABCDEF";//定義字符串
char s2[7] = { 0 };
int sz = sizeof(s1) / sizeof(s1[0]) - 1;//計算字符串的長度,
//字符串中隱藏着一個“\0”,所以計算出來的數要減去1纔是字符串中元素的個數
printf("please input a string(include 6 character):");
scanf("%s", &s2);
printf("%d\n", judge_char(s1, s2, sz));
system("pause");
return 0;
}
方法二:
//該方法所用的思想爲把一個字符串拷貝之後拼接到後面形成如下形式:
//ABCDEFABCDEF 若另一個字符串爲原字符串旋轉後得到的 那麼這個字符串一定是這個
//拼接後的字符串的子串
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <Windows.h>
#include <string.h>
#include <stdlib.h>
#define N 7
int judge_char(char *s1, char *s2)//
{
char *p = malloc(strlen(s1) + strlen(s1) + 1);//開闢動態內存空間,兩個
//字符串的長度加上一個'\0'的長度
strcpy(p, s1);//把字符串s1的內容拷貝到p
strcat(p, s1);//把字符串p與s1拼接到一起
//printf("p = %s\n", p);
if (strstr(p, s2) == NULL)//strstr函數是判斷後者是否爲前者的子串,
//若不是返回NULL
{
return 0;
}
return 1;
}
int main()
{
char s1[N] = "ABCDEF";
char s2[N] = { 0 };//定義兩個字符串
printf("please input a character string(include 6 character):");
scanf("%s", &s2);
printf("%d", judge_char(s1, s2));
system("pause");
}