텍스트의 단어를 다른 주어진 단어로 바꾸는 C 프로그램
세 개의 문자열 'str' 'oldW' 및 'newW'가 주어졌습니다. 작업은 'oldW'라는 단어가 나타나는 모든 항목을 찾아 'newW'라는 단어로 바꾸는 것입니다. 예:
Input : str[] = 'xxforxx xx for xx' oldW[] = 'xx' newW[] = 'geeks' Output : geeksforgeeks geeks for geeks권장 사항: 해결해 보세요. 관행 먼저 솔루션으로 넘어가기 전에
아이디어는 원래 문자열을 순회하여 문자열에서 이전 단어가 나타나는 횟수를 계산하는 것입니다. 이제 새 단어를 대체할 수 있을 만큼 충분한 크기의 새 문자열을 만듭니다. 이제 단어를 대체하여 원래 문자열을 새 문자열로 복사하십시오.
구현:
C // C program to search and replace // all occurrences of a word with // other word. #include #include #include // Function to replace a string with another // string char * replaceWord ( const char * s const char * oldW const char * newW ) { char * result ; int i cnt = 0 ; int newWlen = strlen ( newW ); int oldWlen = strlen ( oldW ); // Counting the number of times old word // occur in the string for ( i = 0 ; s [ i ] != ' ' ; i ++ ) { if ( strstr ( & s [ i ] oldW ) == & s [ i ]) { cnt ++ ; // Jumping to index after the old word. i += oldWlen - 1 ; } } // Making new string of enough length result = ( char * ) malloc ( i + cnt * ( newWlen - oldWlen ) + 1 ); i = 0 ; while ( * s ) { // compare the substring with the result if ( strstr ( s oldW ) == s ) { strcpy ( & result [ i ] newW ); i += newWlen ; s += oldWlen ; } else result [ i ++ ] = * s ++ ; } result [ i ] = ' ' ; return result ; } // Driver Program int main () { char str [] = 'xxforxx xx for xx' ; char c [] = 'xx' ; char d [] = 'Geeks' ; char * result = NULL ; // oldW string printf ( 'Old string: %s n ' str ); result = replaceWord ( str c d ); printf ( 'New String: %s n ' result ); free ( result ); return 0 ; }
산출: Old string: xxforxx xx for xx New String: GeeksforGeeks Geeks for Geeks
시간 복잡도 : 에)
보조 공간: O(n)
방법 2: 이 방법에는 문자열의 내부 업데이트가 포함됩니다. 새 문자를 삽입할 때 추가 공간만 사용하므로 더 효율적입니다.
구현:
C // C Program to replace a word in a text by another given // word by inplace updation #include #include #include void replaceWord ( char * str char * oldWord char * newWord ) { char * pos temp [ 1000 ]; int index = 0 ; int owlen ; owlen = strlen ( oldWord ); // Repeat This loop until all occurrences are replaced. while (( pos = strstr ( str oldWord )) != NULL ) { // Bakup current line strcpy ( temp str ); // Index of current found word index = pos - str ; // Terminate str after word found index str [ index ] = ' ' ; // Concatenate str with new word strcat ( str newWord ); // Concatenate str with remaining words after // oldword found index. strcat ( str temp + index + owlen ); } } int main () { char str [ 1000 ] oldWord [ 100 ] newWord [ 100 ]; printf ( 'Enter the string: ' ); gets ( str ); printf ( 'Enter the word to be replaced: ' ); gets ( oldWord ); printf ( 'Replace with: ' ); gets ( newWord ); replaceWord ( str oldWord newWord ); printf ( ' n Modified string: %s' str ); return 0 ; }
입력: 1 xxforxx xx for xx xx geeks산출:
geeksforgeeks geeks for geeks
시간 복잡도: O(n)
보조 공간: O(1)