2016-10-28 18 views
0

這裏我試圖找到一個字符串中的子字符串,顛倒子字符串並將其替換爲原始字符串。如果我用if條件替換while循環,它適用於第一次出現。但我希望它適用於多次發生。 如果我在while循環中運行它(while(str = strstr(str,substr)),它會導致分段錯誤,我正在使用代碼塊IDE。 那麼,我該如何改變代碼以便它可以工作在多個occurances如何在另一個子查找中找到多個子字符串並執行「某些」操作?

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

int main() 
{ 
char *str = malloc(100); 
char *sbstr = malloc(20); 
int i=0,flag=1;; 
printf("%s\n","Enter string"); 
gets(str); 
printf("%s\n","Enter substring"); 
gets(sbstr); 
///////////////////////////////////////////////////////////// 

while(str = strstr(str,sbstr)) 
    { 

     memcpy(str,strrev(sbstr),strlen(sbstr)); 

    } 

//////////////////////////////////////////////////// 
    printf("%s",str); 
    return 0; 

} 
+1

當您使用'函數strncpy()',它在的末尾添加一個空結束複製的字符串由於您正在複製到源字符串中,因此您已將字符串截斷爲該點。 – Barmar

+0

在我嘗試深入您的代碼之前,您是否已踩過它通過諸如GDB的調試器? Valgrind也是檢查內存泄漏的有用工具。另外,一定要用'-Wall -Wextra'編譯。 – RastaJedi

+2

使用'memcpy()'而不是'strncpy()',所以它不會添加空終止符。 – Barmar

回答

0

更好和更有效循環的作品是:(仔細看一下就可以了)

char* first_p; //will store the address of the first character of sbstr in str if it does 


while(i < LENGTH_OF_STR) //if smaller than the length of the main array 
{ 

    if(str[i] == sbstr[k]) 
    { 
     k++: 
     if(k == LENGTH_OF_SBSTR) 
     { 
      //sbstr is in str 
      first_p = str+i-LENGTH_OF_SBSTR-1; //now first_p stores the pointer to the first letter 
      reverse(first_p,LENGTH_OF_SBSTR);// reversing the string 
      break; 
     } 
    } 
    else 
    { 
     k = 0; 
    } 

    i++; 

} 

void reverse(char *toReverse,int len) 
{ 
    int i; 
    char temp; 

    for (i=len-1; i >= len/2; i--) 
    { 
     temp = toReverse[i]; 
     toReverse[i] = toReverse[len-1-i]; 
     toReverse[len-1-i] = temp; 
    } 

} 
+0

如果您認爲這有幫助,請爲投稿投票:)。 –

相關問題