用 C 中的另一个词替换字符串中的一个词
Replace a word in a string with another word in C
#include <stdio.h>
#include <string.h>
int main(void){
char sen[100];
char word[30];
char rep[30];
printf("Enter a sentence> ");
gets(sen);
printf("Enter a word to compare> ");
gets(word);
printf("Enter a word to replace with> ");
gets(rep);
int sen_len = strlen(sen);
int word_len = strlen(word);
char temp[30];
char retSen[100];
char rest[70];
int i;
int y=0;
for(i=0; i<sen_len; i++){
//Loop through characters in sentence until you reach a whitespace. ie, extract a word and put it in temp.
if(sen[i] == ' '){
//Compare the word with target word
if(!strcmp(temp, word)){
//In case of match, copy the part upto but not including the matching word and put it in the final string (retSen)
strncpy(retSen, sen, sen_len-i);
}else{
//Clear temp and skip to next iteration
y=0;
temp[0] = '[=10=]';
continue;
}
}
y++;
//Repeatedly populate y with a word from sen
temp[y] = sen[i];
}
int x=0;
for(int j=i; j<sen_len; j++){
//Populate another char array with the rest of the sentence after the matching word.
rest[x] = sen[j];
}
//Join the part upto the matching word with the replacing word.
strcat(retSen, rep);
//Then join the rest of the sentence after the matching word to make the full string with the matching word replaced.
strcat(retSen, rest);
puts(retSen);
return 0;
}
我正在尝试制作一个程序,它将接受一个句子、一个要替换的目标词和另一个要替换目标的词。此代码无效。由于某种原因,它只是打印替换词 + 'a' 。我该如何修复此代码?
在 C 中,您需要构建自己的字符串替换函数。我认为您的用例可以很好地利用 strtok()
、strcat()
和 strncat()
函数,
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Prototypes:
int searchForWord( const char * haystack, const char * needle );
char * searchAndReplace( const char * haystack, const char * needle, const char * newNeedle );
/**
* main
*/
int main()
{
const char * sentence = "The quick brown fox jumped over the lazy dog." ;
const char * wordToReplace = "fox" ;
const char * replacementWord = "turtle" ;
// ... Search and replace...
char * newSentence = searchAndReplace( sentence, wordToReplace, replacementWord ) ;
// ... Show the result
if ( newSentence ) {
printf( "%s\n", newSentence ) ;
free( newSentence ) ;
} else {
printf( "%s\n", sentence ) ;
}
return 0;
}
/**
* Take a sentence, and replace the first occurrence of a word with another word.
*
* Parameters:
* haystack: the original sentence
* needle: the word to search and replace
* newNeed: the word to use as replacement
*
* Returns:
* A new modified string, or NULL if the word was never found.
*
* Note:
* The result is dynamically allocated so it mut be freed once no longer needed.
*/
char * searchAndReplace( const char * haystack, const char * needle, const char * newNeedle )
{
// ... Is the word in the sentence?
int offset = searchForWord( haystack, needle ) ;
if ( offset < 0 ) {
fprintf( stderr, "searchAndReplace: %s not found in the given setence\n", needle );
return NULL;
}
// ... From the found offset, determine the end offset of the word
int offsetEnd = offset + strlen(needle);
// ... Create a new buffer that will contain the modified sentence
int newSize = strlen( haystack ) - strlen( needle ) + strlen( newNeedle ) + 1 ;
char * result = (char*)malloc( newSize * sizeof(char) ) ;
// ... Initialize the new buffer to a zero-length string
result[ 0 ] = '[=10=]';
// ... Build the new sentence: first part (before the found word)
if ( offset > 0 ) {
strncat( result, haystack, offset) ;
}
// ... Build the new sentence: replaced word
strcat( result, newNeedle ) ;
// ... Build the new sentence: last part
strncat( result, &haystack[ offsetEnd ], strlen(&haystack[ offsetEnd ]) ) ;
return result ;
}
/**
* Find the location of a word in a sentence, assuming words are whitespace-
* delimited.
*
* Returns: offset of the word in the sentence, or -1 if not found
*/
int searchForWord( const char * haystack, const char * needle )
{
int result = -1 ;
const char * delims = " \n\r\t" ; // whitespaces
// ... Get a copy of haystack, as strtok() will alter it
char * copy = strdup(haystack) ;
// ... For each word in the sentence
for ( char *p = strtok( copy, delims ); p != NULL; p = strtok( NULL, delims ) ) {
// ... If the word matches what we're looking for
if ( strcmp( p, needle ) == 0 ) {
// ... Set the offset in the sentence
result = p - ©[ 0 ] ;
// ... We're done searching
break ;
}
}
// .... Avoid memory leaks
free( copy ) ;
// ... Return whatever we found (or not)
return result ;
}
#include <stdio.h>
#include <string.h>
int main(void){
char sen[100];
char word[30];
char rep[30];
printf("Enter a sentence> ");
gets(sen);
printf("Enter a word to compare> ");
gets(word);
printf("Enter a word to replace with> ");
gets(rep);
int sen_len = strlen(sen);
int word_len = strlen(word);
char temp[30];
char retSen[100];
char rest[70];
int i;
int y=0;
for(i=0; i<sen_len; i++){
//Loop through characters in sentence until you reach a whitespace. ie, extract a word and put it in temp.
if(sen[i] == ' '){
//Compare the word with target word
if(!strcmp(temp, word)){
//In case of match, copy the part upto but not including the matching word and put it in the final string (retSen)
strncpy(retSen, sen, sen_len-i);
}else{
//Clear temp and skip to next iteration
y=0;
temp[0] = '[=10=]';
continue;
}
}
y++;
//Repeatedly populate y with a word from sen
temp[y] = sen[i];
}
int x=0;
for(int j=i; j<sen_len; j++){
//Populate another char array with the rest of the sentence after the matching word.
rest[x] = sen[j];
}
//Join the part upto the matching word with the replacing word.
strcat(retSen, rep);
//Then join the rest of the sentence after the matching word to make the full string with the matching word replaced.
strcat(retSen, rest);
puts(retSen);
return 0;
}
我正在尝试制作一个程序,它将接受一个句子、一个要替换的目标词和另一个要替换目标的词。此代码无效。由于某种原因,它只是打印替换词 + 'a' 。我该如何修复此代码?
在 C 中,您需要构建自己的字符串替换函数。我认为您的用例可以很好地利用 strtok()
、strcat()
和 strncat()
函数,
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Prototypes:
int searchForWord( const char * haystack, const char * needle );
char * searchAndReplace( const char * haystack, const char * needle, const char * newNeedle );
/**
* main
*/
int main()
{
const char * sentence = "The quick brown fox jumped over the lazy dog." ;
const char * wordToReplace = "fox" ;
const char * replacementWord = "turtle" ;
// ... Search and replace...
char * newSentence = searchAndReplace( sentence, wordToReplace, replacementWord ) ;
// ... Show the result
if ( newSentence ) {
printf( "%s\n", newSentence ) ;
free( newSentence ) ;
} else {
printf( "%s\n", sentence ) ;
}
return 0;
}
/**
* Take a sentence, and replace the first occurrence of a word with another word.
*
* Parameters:
* haystack: the original sentence
* needle: the word to search and replace
* newNeed: the word to use as replacement
*
* Returns:
* A new modified string, or NULL if the word was never found.
*
* Note:
* The result is dynamically allocated so it mut be freed once no longer needed.
*/
char * searchAndReplace( const char * haystack, const char * needle, const char * newNeedle )
{
// ... Is the word in the sentence?
int offset = searchForWord( haystack, needle ) ;
if ( offset < 0 ) {
fprintf( stderr, "searchAndReplace: %s not found in the given setence\n", needle );
return NULL;
}
// ... From the found offset, determine the end offset of the word
int offsetEnd = offset + strlen(needle);
// ... Create a new buffer that will contain the modified sentence
int newSize = strlen( haystack ) - strlen( needle ) + strlen( newNeedle ) + 1 ;
char * result = (char*)malloc( newSize * sizeof(char) ) ;
// ... Initialize the new buffer to a zero-length string
result[ 0 ] = '[=10=]';
// ... Build the new sentence: first part (before the found word)
if ( offset > 0 ) {
strncat( result, haystack, offset) ;
}
// ... Build the new sentence: replaced word
strcat( result, newNeedle ) ;
// ... Build the new sentence: last part
strncat( result, &haystack[ offsetEnd ], strlen(&haystack[ offsetEnd ]) ) ;
return result ;
}
/**
* Find the location of a word in a sentence, assuming words are whitespace-
* delimited.
*
* Returns: offset of the word in the sentence, or -1 if not found
*/
int searchForWord( const char * haystack, const char * needle )
{
int result = -1 ;
const char * delims = " \n\r\t" ; // whitespaces
// ... Get a copy of haystack, as strtok() will alter it
char * copy = strdup(haystack) ;
// ... For each word in the sentence
for ( char *p = strtok( copy, delims ); p != NULL; p = strtok( NULL, delims ) ) {
// ... If the word matches what we're looking for
if ( strcmp( p, needle ) == 0 ) {
// ... Set the offset in the sentence
result = p - ©[ 0 ] ;
// ... We're done searching
break ;
}
}
// .... Avoid memory leaks
free( copy ) ;
// ... Return whatever we found (or not)
return result ;
}