我这里有这段代码
#include <stdio.h>
#include <string.h>
#include<conio.h>
void main()
{
char s[] = "All work and no play makes Jack a dull boy.";
char word[10],rpwrd[10],str[10][10];
int i=0,j=0,k=0,w,p;
printf("All work and no play makes Jack a dull boy.\n");
printf("\nENTER WHICH WORD IS TO BE REPLACED\n");
scanf("%s",word);
printf("\nENTER BY WHICH WORD THE %s IS TO BE REPLACED\n",word);
scanf("%s",rpwrd);
p=strlen(s);
for (k=0; k<p; k++)
{
if (s[k]!=' ')
{
str[i][j] = s[k];
j++;
}
else
{
str[i][j]='\0';
j=0; i++;
}
}
str[i][j]='\0';
w=i;
for (i=0; i<=w; i++)
{
if(strcmp(str[i],word)==0)
strcpy(str[i],rpwrd);
printf("%s ",str[i]);
}
getch();
}
如何更换“杰克”这个词?像
输出:
All work and no play makes Jack a dull boy.
Enter ther word Jack to be Replaced
Mark
Tom
All work and no play makes Mark a dull boy.
All work and no play makes Tom a dull boy.
没有搜索整个句子。
THX
答案 0 :(得分:2)
没有搜索整个句子。
你必须搜索整行:
char sentence[] = "The quick brown fox jumped over the lazy dog.";
const char *to_replace = "fox";
const char *replacement = "dragon";
char *pos = strstr(sentence, to_replace);
// if found
if (pos != NULL) {
// The new string
size_t newlen = strlen(sentence) - strlen(to_replace) + strlen(replacement);
char new_sentence[newlen + 1];
// Copy the part of the old sentence *before* the replacement
memcpy(new_sentence, sentence, pos - sentence);
// Copy the replacement
memcpy(new_sentence + (pos - sentence), replacement, strlen(replacement));
// Copy the rest
strcpy(new_sentence + (pos - sentence) + strlen(replacement), pos + strlen(to_replace));
printf("Old: %s\nNew: %s\n", sentence, new_sentence);
}
答案 1 :(得分:0)
最快的方法是分配一个strlen (s) - strlen (word) + strlen (rpwrd) + 1
的新字符串。然后使用strstr
函数查找要替换的单词并将该单词复制到新字符串中,附加新单词,然后将原始句子的其余部分复制到新字符串中。
答案 2 :(得分:0)
您需要声明char*
并使用malloc
或calloc
为其分配动态内存。当单词比被替换的单词长时,会出现这种情况
其次,<string.h>
中有许多函数来搜索字符串并用给定的字符串替换它。
有strstr
- 函数,它定位子字符串并返回字符串内的位置。
虽然大约是C++
,但请查看here以获取<string.>
- 标题的参考。
答案 3 :(得分:0)
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] ="This is a simple string made with simple code";
char * pch;
int i=0,count=0;
for(i=0;i<strlen(str);i++){
if(str[i]=='s'&& str[i+1]=='i'&&str[i+2]=='m'&&str[i+3]=='p' && str[i+4]=='l' && str[i+5]=='e'){
count++;
}
}
for(i=1;i<=count;i++){
pch = strstr (str,"simple");
strncpy (pch,"sample",6);
}
puts (str);
return 0;
}
答案 4 :(得分:-1)
这可能有效:
#include<bits/stdc++.h>
using namespace std;
int main()
{
char str[] ="xxxxforxxxx xxxx for xxxx";
int n=sizeof(str)/sizeof(str[0]);
string old ="xxxx";
int oldlen=old.length();
string news ="geeks";
string final="";
for(int i=0;i<=n-oldlen-1;i++)
{
string check="";
for(int j=i;j<old.length()+i;j++)
{
check+=str[j];
}
if(old==check)
{
final+=news;
i=i+oldlen-1;
}
else
{
final+=str[i];
}
}
cout<<final;
}