我在撰寫一個獲取兩個單詞并找到最長公共后綴的程式時遇到了麻煩。每當我嘗試將單詞中的內容復制到我的新字串“后綴”中時,我都會收到垃圾值,并且我正在努力找出我出錯的地方。任何和所有反饋表示贊賞!
void longest_suffix(char word1[], char word2[]){
char suffix[20];
int count = 0;
int end = strlen(word2) - 1;
int j = 0;
for(int i = strlen(word1)- 1; i >= 0; i--){
if(word1[i] == word2[end - j]){
count ;
}
j ;
}
int z = 0, k = 0;
for(k = 0; k < count; k ){
suffix[k] == word2[end - count z];
z ;
}
suffix[k] = '\0';
printf("%s", suffix);
}
uj5u.com熱心網友回復:
我會以稍微不同的方式處理這個問題。無需復制字串。如果有一個共同的后綴,它已經存在于word1and 中word2,并且已經以空值結尾。
void longest_suffix(char word1[], char word2[]){
char *p1 = word1 strlen(word1) - 1;
char *p2 = word2 strlen(word2) - 1;
char *suffix = NULL;
while (p1 >= word1 && p2 >= word2) {
if (*p1 == *p2) {
suffix = p1;
}
p1--;
p2--;
}
printf("suffix: %s\n", suffix);
}
而且:這個函式簽名不是很好。而且您正在從一個顯然不會列印輸出而不是回傳結果的函式進行列印。考慮:
const char *longest_suffix(const char *word1, const char *word2) {
const char *p1 = word1 strlen(word1) - 1;
const char *p2 = word2 strlen(word2) - 1;
const char *suffix = NULL;
while (p1 >= word1 && p2 >= word2) {
if (*p1 == *p2) {
suffix = p1;
}
p1--;
p2--;
}
return suffix;
}
我不會從這樣的函式中列印或分配。如果呼叫者想要一個副本,他們可以呼叫strdup結果(如果它不是 NULL)。
uj5u.com熱心網友回復:
這是一個解決方案:
#include <assert.h>
#include <stdio.h>
#include <string.h>
#define MIN(x, y) (((x) < (y)) ? (x) : (y))
static void longest_suffix(const char word1[], const char word2[])
{
int len1 = strlen(word1);
int len2 = strlen(word2);
int minlen = MIN(len1, len2);
int i;
assert(word1[len1] == word2[len2] && word1[len1] == '\0');
for (i = 1; i <= minlen; i )
{
if (word1[len1 - i] != word2[len2 - i])
break;
}
printf("[%s] = ", &word1[len1 - i 1]);
printf("[%s]: ", &word2[len2 - i 1]);
printf("[%s] vs [%s]\n", word1, word2);
assert(strcmp(&word1[len1 - i 1], &word2[len2 - i 1]) == 0);
}
int main(void)
{
longest_suffix("abc.c", "def.c");
longest_suffix("basename.c", "dirname.c");
longest_suffix("spooky spells - abracadabra", "abracadabra");
longest_suffix("abracadabra", "spooky spells - abracadabra");
longest_suffix("xyz", "xyz");
longest_suffix("c", "c");
return 0;
}
總的來說,最好將確定最長后綴與列印它分開。實際上,您應該經常將 I/O 與計算分開。當 I/O 要求發生變化時,它可以更輕松地重用計算。
輸出:
[.c] = [.c]: [abc.c] vs [def.c]
[name.c] = [name.c]: [basename.c] vs [dirname.c]
[abracadabra] = [abracadabra]: [spooky spells - abracadabra] vs [abracadabra]
[abracadabra] = [abracadabra]: [abracadabra] vs [spooky spells - abracadabra]
[xyz] = [xyz]: [xyz] vs [xyz]
[c] = [c]: [c] vs [c]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/359890.html
