给定三个字符串“ str”,“ oldW”和“ newW”。该任务是找到单词“ oldW”的所有出现,然后替换为单词“ newW”。
例子:
Input : str[] = "xxforxx xx for xx",
oldW[] = "xx",
newW[] = "geeks"
Output : geeksforgeeks geeks for geeks
我们的想法是穿越原始字符串并计算在字符串中出现旧词的次数。现在制作一个足够大的新字符串,以便可以替换新单词。现在,用单词替换将原始字符串复制到新字符串。
// 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] != '\0'; 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] = '\0';
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
方法2:此方法涉及到字符串的就地更新。由于它仅使用多余的空间来插入新字符,因此效率更高。
#include
using namespace std;
int main()
{
// code
int t;
cin >> t;
cin.ignore();
while (t--) {
string s;
getline(cin, s);
string x, y;
getline(cin, x);
getline(cin, y);
reverse(s.begin(), s.end());
reverse(x.begin(), x.end());
reverse(y.begin(), y.end());
int ls = s.length(), lx = x.length(), ly = y.length();
int d = ly - lx;
int ct = 0;
int i = 0, j = 0;
while (i < ls) {
string temp = "";
for (int k = 0; k < lx; k++) {
temp += s[i + k];
}
if (temp == x) {
ct++;
i = i + lx;
}
else {
i = i + 1;
}
}
for (int i = 0; i < ct * d; i++)
s += ' ';
i = ls - 1;
j = ls + ct * d - 1;
while (i >= 0 && j >= 0) {
string temp = "";
for (int k = 0; k < lx; k++) {
if (i < (lx - 1 - k))
break;
temp += s[i - (lx - 1 - k)];
}
if (temp == x) {
int k = ly - 1;
while (k >= 0)
s[j--] = y[k--];
i = i - lx;
}
else {
s[j--] = s[i--];
}
}
reverse(s.begin(), s.end());
cout << s << endl;
}
return 0;
}
输入:
1
xxforxx xx for xx
xx
geeks
输出:
geeksforgeeks geeks for geeks
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。