因为对strncpy函数不熟练所以wa了几次还找不到原因,最后发现是strcpy重新复制时,若新复制的字符串短,原有比新串长的部分会被保留。所以每次复制前要使用memset函数。
刚学习,代码比较简陋,效率也不高。
A character string is said to have period k if it can be formed by concatenating one or more repetitionsof another string of length k. For example, the string ”abcabcabcabc” has period 3, since it is formedby 4 repetitions of the string ”abc”. It also has periods 6 (two repetitions of ”abcabc”) and 12 (onerepetition of ”abcabcabcabc”).Write a program to read a character string and determine its smallest period.
Input
The first line oif the input file will contain a single integer N indicating how many test case that yourprogram will test followed by a blank line. Each test case will contain a single character string of upto 80 non-blank characters. Two consecutive input will separated by a blank line.
Output
An integer denoting the smallest period of the input string for each input. Two consecutive output areseparated by a blank line.
Sample Input
1
HoHoHoSample
Output
2
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int macth_string(char*, char*, int, int);
char s[1000];
char ss[1000];
int main()
{
int t = 0;
scanf("%d", &t);
while(t--)
{
int place = 0;
int flag = -1;
int len = 0;
scanf("%s", s);
memset(ss, 0, sizeof(ss));
strncpy(ss, s, 1);
//printf("\n");
len = strlen(s);
while(place < strlen(s))
{
flag = macth_string(ss, s, place, strlen(ss));
if(flag) place += strlen(ss); //this could merge into macth_string; don't merge!
else
{
strncpy(ss, s, strlen(ss)+1);
place = strlen(ss);
}
}
//output ss and strlen(ss)
printf("%ld\n", strlen(ss));
if(t)
printf("\n");
}
return 0;
}
int macth_string(char* ss, char* s, int place, int ss_len)
{
int m_flag = 1;
//macthing from tag place, if failure return 0
for(int i=0; i<ss_len; i++)
{
if(ss[i] != s[place+i])
{
m_flag = 0;
break;
}
}
//if matching success, return 1
return m_flag;
}