2017-09-07 49 views
-3

我在C中很新,我想知道如何找出兩個相同字符之間的距離。找到兩個字符之間的距離

例如;我們有字符串「蝙蝠俠」,而字母「a」會給我們第一個「a」和第二個/最後一個「a」之間的距離。在這種情況下,我們會有2個結果。

這是我的代碼到目前爲止,但我很不確定該怎麼做 - 所以請幫助我。而且我也很確定這不是一個有效的方法。

int distance(char* s, char c) { 
    int res = -1; 
    int i = 0; 

    while(s[i]) { 
    int j = i+1; 

    while(s[j]) { 
     if (s[j] == c) { 
     res = j-i; 
     break; 
     } 
     j++; 
    } 
    i++; 
    } 
    return res-1; 
} 

我知道我做錯了什麼,但我不知道是什麼。 在此先感謝

+3

我建議你花一些時間來閱讀[如何調試小程序(https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)由埃裏克利珀,並學習如何使用調試器逐行執行代碼。 –

+5

目前還不清楚你在問什麼。你是說這個程序不工作?如果不是的話,那究竟是什麼問題,以及你到目前爲止所進行的調查? – lurker

+1

你不需要兩個嵌套循環,一個會做。當你發現'c'設置'lastindex'時,如果'firstindex'從未設置過,那麼也要設置它。確保你處理的角落案件,如一次或沒有。 –

回答

0

簡單sollution返回距離(從1,如果字符是連續的)或0,如果沒有距離(只有一個字符,空字符串,沒有字符)

size_t distance(const char *str, char c) 
{ 
    size_t result = 1; 

    while (*str && *str != c) str++; 
    if (*str) str++; 
    while (*str && *str != c) 
    { 
     result++; 
     str++; 
    } 
    return *str ? result : 0; 
} 
1

的功能是沒有意義的,因爲它應該確定字符串中字符的存在兩次。

該函數可以使用標準C函數strchr來編寫。下面顯示了使用strchr的功能。在字符串中缺少字符或僅遇到一次字符的情況下,它將返回0。否則,該函數返回差異n2 - n1,其中n2n1是該角色的兩個第一位置。

#include <stdio.h> 
#include <string.h> 

size_t distance(const char *s, char c) 
{ 
    size_t n = 0; 

    const char *p; 

    if (c && (s = strchr(s, c)) != NULL && (p = strchr(s + 1, c)) != NULL) 
    { 
     n = p - s; 
    } 

    return n; 
} 

int main(void) 
{ 
    printf("distance(\"batman\", 'a') = %zu\n", distance("batman", 'a')); 

    return 0; 
} 

程序輸出是

distance("batman", 'a') = 3 

如果你想獲得價值2然後就減去1從返回的值,如果它不等於0

還有一個辦法將距離作爲角色的兩次連續出現之間的所有距離中的最小值。

+1

問題是如果你減去1,沒有辦法知道是否有任何距離 –

+0

@ PeterJ_01沒有問題。我在我的回答中描述,在扣除之前應檢查返回值是否等於零。 –

+0

你不明白。我使用相同的size_t,並且零必須指示錯誤(例如未找到字符)。 –

0

下面是解決您的問題的簡單方法。你需要記住檢查空終止字符!如果char只發現一次,如果根本找不到,或者它們之間的距離爲0,它將返回0。否則,返回找到的第一個字符和第二個字符之間的距離。

#include <stdio.h> 
size_t distance(char* s, char c) { 
    size_t res = 0; 
    size_t i = 0; 

    while(s[i] != c && s[i] != '\0') {//while it doesn't find the first char and it's not the null terminating char(so that you don't keep going indefinitely) 
    ++i; 
    } 
    if (s[i] != '\0') {//if it didn't stop because it found the null terminating char, keep going 
    ++i; 
    while(s[i] != c && s[i] != '\0') {//do the same thing as the first while, but count 
     ++i; 
     ++res; 
    } 
    } 

    return s[i] != '\0' ? res : 0;//if the second time it searches for the char it didn't find the null-terminating char, it means it found the char you want, so return res, otherwise return 0 
} 

int main() { 
    char* str = "batman"; 
    printf("%d",distance(str, 'a')); 
    return 0; 
} 
+0

'int'不好,因此距離會大於INT_MAX? –

+0

@ PeterJ_01循環沒有嵌套。 – chux

+0

@chux權利 - 不太可讀的風格。 –