【发布时间】:2022-01-11 04:23:45
【问题描述】:
这里是初学者,试图弄清楚如何在 C 中查找和打印最长的公共前缀。
我在这里有一个程序的基地。
#include <stdio.h>
void findprefix(char *str1, char *str2, char *found);
int main(void) {
char str1[100];
char str2[100];
char found[10] = { '\0' };
printf("\nGive string 1: ");
scanf("%99s", str1);
printf("\nGive string 2: ");
scanf("%99s", str2);
//Print prefix
findprefix(str1, str2, found);
printf("%s", found);
return 0;
}
//Function to find the longest common prefix
void findprefix(char *str1, char *str2, char *found) {
int i, j;
for () {
if () {
}
}
}
最初的想法是在函数中使用for 循环和if 语句,但我不确定如何。
【问题讨论】:
-
我想你希望“findprefix”函数返回一个int,最长公共前缀的长度。
-
@MarkLavin
size_t会更合适。 -
如果输入可以达到100字节,为什么
found[10]只有10字节? -
调用后的字符串你关心吗?那么它们应该是
const char *和malloc。或许更好的方法是将char的数量返回相同;可以传递给printf“%.*s”吗?
标签: c c-strings string-comparison prefix function-definition