⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 prog6_11.cpp

📁 一本语言类编程书籍
💻 CPP
字号:
// Program 6.11 Replacing words in a string
#include <iostream>
#include <string>
using std::cout;
using std::cin;
using std::endl;
using std::string;

int main() {
  // Read the string from the keyboard
  string text;
  cout << endl << "Enter a string terminated by #:" << endl;
  std::getline(cin, text, '#');

  // Get the word to be replaced
  string word;
  cout << endl << "Enter the word to be replaced: ";
  cin >> word;

  // Get the replacement
  string replacement;
  cout << endl << "Enter the replacement word: ";
  cin >> replacement;

  if(word == replacement) {
    cout << endl 
         << "The word and its replacement are the same." << endl
         << "Operation aborted." << cout;
    exit(1);
  }

  // Find the start of the first occurrence of word
  size_t start = text.find(word);

  // Now find and replace all occurrences of word
  while(start != string::npos) {
    text.replace(start, word.length(), replacement);         // Replace word
    start = text.find(word, start + replacement.length());
  }

  cout << endl 
       << "Your string is now:" << endl 
       << text << endl;

  return 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -