字符串manipluator在C 中使用所有功能

string manipluator to use all function in c++

本文关键字:功能 manipluator 字符串      更新时间:2023-10-16

编写一个程序来操纵字符串。在此程序中,请从用户输入打击(最多500个字母(,从文件初始化或读取整个段落,并在类中提供以下功能:

a(声明类

b(成员函数:搜索字(搜索特定单词(

c(成员函数:搜索机(搜索特定字母(

d(成员函数:WordCount(计算总单词(

e(成员函数:lettercount(仅计算所有字母,例如'a','a'(

f(成员函数:findreplaceword(查找并替换一个单词(

g(成员函数:FindReplaceTter(查找并替换字母(

h(成员函数:摘要(在段落中显示每个字母的频率的摘要(

i(当然,用户期望菜单了解您段落的可用功能。

在下面尝试了代码,但是我需要开关,以便用户可以尝试各种函数,用户可以输入段落

#include <iostream>
#include <string>
using namespace std;
char str[100] = "This string contains many alphabets";
char paragraph,sentence;
void SearchWord(){
  string paragraph;
    cout << "Please enter your paragraph:";
    getline (cin,paragraph);
    cout << "Hello, your paragraph is " << paragraph << "!n";
    string paragraph1 = paragraph;
//  cout << sentence << endl;
    cout << "The size of your paragraph = " << paragraph.size() << " characters. nn";
    string word;

    cout << "Please enter the word you are searching for:";
        getline (cin,word);
        cout << "Hello, your word is " << word << "!n";
    size_t found = paragraph.find(word);
bool wordsearch = true;
while (paragraph.find(word) != string::npos)  {

  if (paragraph.find(word) == string::npos)
 cout << "" << word << " does not exist in the sentence" << endl;
        std::size_t found = paragraph.find(word);
  if (found!=std::string::npos)
    std::cout << "'word' found at: " << found << 'n';

    break;
    }while (wordsearch = true);

}
void SearchLetter(){
}
void WordCount(){
  int i,count=1;
    for(i=0;str[i]!='';++i)
    {
        if(str[i]==' ')
            count++;
    }
    cout<<"nThere are "<<count<<" words in the given string";
}
void LetterCount(){
}
void FindReplaceWord(){
}
void FindReplaceLetter(){
}
void Summary(){
  int i = 0, alphabet[26] = {0}, j;
   while (str[i] != '') {
      if (str[i] >= 'a' && str[i] <= 'z') {
         j = str[i] - 'a';
         ++alphabet[j];
      }
      ++i;
   }
   cout<<"frequency of all alphabets in the string is:"<<endl;
   for (i = 0; i < 26; i++)
      cout<< char(i + 'a')<<" : "<< alphabet[i]<< endl;
}

int main()
{
  // WordCount();
  //SearchLetter()
 // SearchWord();
 //  Summary(); 
    return 0;
}

您要实现的目标是典型的菜单选择。您向用户显示了他可以选择的操作列表。每个动作都有您在菜单中显示的相关数字或字母。

然后您从std::cin阅读了希望的选择。因此,字母,数字或数字,菜单中显示的内容。

然后您使用C switch语句。C 开关语句采用一个变量,例如char或int作为其参数。然后,有许多案例条款。在您定义的每个情况条款中,如果"案例"充满了充实,应该会发生什么。例子。用户输入一个整数号码。像在int selection; std::cin>>selection;中一样,现在您可以在不同的案例语句中评估此Interger。例如:case 1:。如果选择是1,则执行案例语句之后的代码。直到break;语句到来。

您可以随意具有尽可能多的case语句。但是没有双打,只有适合您选择变量类型的常数。

switch构造可以使您免于冗长的速度,如果否则,如果否则,如果其他。。语句。

在下面的代码中,我实施了带有选择和大"开关案例"循环的菜单。您可以选择所有功能,这些功能将使用请求的功能执行。

#include <string>
#include <iostream>
#include <regex>
#include <sstream>
#include <fstream>
#include <map>
#include <algorithm>
#include <iterator>
#include <iomanip>
// Some test data. This is the same, as if this data would be in a file
std::istringstream inputTestFileLong{ R"(Lorem ipsum dolor sit amet, arcu est nonummy molestie 
vel magna porttitor. Eget vel integer, turpis condimentum ante, integer elit dolor, cum necessitatibus, 
vel proin. Risus nec arcu rutrum malesuada mauris, fringilla viverra, augue luctus praesentium erat 
elit aenean. Praesent ligula fringilla justo, magna sed wisi, nibh vel vel semper nostrud, vestibulum 
enim vel orci. Pulvinar eget feugiat est, exercitationem ut dui, nascetur dui, condimentum aliquam libero. 
Nunc ullamcorper malesuadamum, justo consectetuer odio quis consequat, mauris morbi, proin vivamus. Augue 
nulla cum, justo vehicula pede cursus nullam donec, fringilla tellus, massa parturient sed elementum, 
vestibulum sit egestas libero dignissim in ut.)" };
// Some additional test data. This is the same, as if this data would be in a file
std::istringstream inputTestFileShort{ "Lorem ipsum dolor" };

// We want to deal with a maximum number of characters
constexpr size_t MaxNumberOfCharacters = 500;
// We will use regurlar expressions to identify a word
const std::regex regexWord("[A-Za-z]+");

// Our Paragraph_Analysis class. All methods and data are define here
class Paragraph_Analysis
{
public:
    // Constructors
    Paragraph_Analysis() {};  // Default, empty. Member variables are already initialized in function body
    Paragraph_Analysis(std::istream& is) { readFromStream(is); }        // Read from a stream
    Paragraph_Analysis(std::string& data) { assignNewString(data); }    // Take a filename, open file and read data from there
    // Search for a word and report, if found or not
    bool searchWord(const std::string& word) { return (paragraph.find(word) != std::string::npos); }
    // Search for a character and report, if found or not
    bool searchCharacter(const char c) { return (paragraph.find(c) != std::string::npos); }
    // Count the words according to the definition, what a word is. Please see regex above
    void wordCount();
    // Count how many letters from the alphabet are in the paragraph
    void letterCount() { std::cout << "nnNumber of letters: " << std::count_if(paragraph.begin(), paragraph.end(), ::isalpha) << "n"; }
    // Find a word in the text and replace it with another one
    void findReplaceWord(const std::string& find, const std::string& replace);
    // Find a character in the text and replace it with another one
    void findReplaceLetter(const char find, const char replace) { findReplaceWord(std::string(1, find), std::string(1, replace)); }
    // Count the frequency of all letters
    void frequencyOfLetter();
    // Open a file and read the text from the file
    void readFromFile(const std::string filename) { std::ifstream ifs(filename); if (ifs) readFromStream(ifs); else std::cerr << "n*** ERRORn"; }
    // Copy the paragraph from another string
    void assignNewString(const std::string& s) { paragraph.assign(s, 0, MaxNumberOfCharacters); }
    // Overwrite inserter and extractor operator for ultra simple input and output
    friend std::ostream& operator << (std::ostream& os, const Paragraph_Analysis& pa) { return os << pa.paragraph; }
    friend std::istream& operator >> (std::istream& is, Paragraph_Analysis& pa) { pa.readFromStream(is); return is; }
protected:
    // Read text from a stream with a given maximum number
    void readFromStream(std::istream& is);
    // This is our data container
    std::string paragraph{};
    // Temproray string to hold converted strings
    std::string modifiedString{};
    // This we will use for counting characters
    std::map<char, unsigned int> letterCounter{};
};

// Read data from a stream. But only up to a limited count
void Paragraph_Analysis::readFromStream(std::istream& is)
{
    // First clear the old data
    paragraph.clear();
    // Read characters. Check for maximum count and for read errors
    char c{};
    while ((paragraph.size() < MaxNumberOfCharacters) && (is.get(c))) 
        paragraph.push_back(c); // Append new read character to paragraph
}
// Count the words in the paragraph
void Paragraph_Analysis::wordCount()
{
    // We will use the std::sregex_token iterator. This is an iterator, that looks
    // for things iour paragraph that are defined in the regex above. So, it will 
    // iterate over all words in the paragraph. It will start with the firts word 
    // and it will end with the last word. The distance betwenn the positions of
    // the first last word and the first word, is the number of words.
    std::cout << "nnNumber of words: "
        << std::distance(
               std::sregex_token_iterator(paragraph.begin(), paragraph.end(), regexWord, 1), // First word
               std::sregex_token_iterator())  // Last word
        << "n";
}
// For replacing strings there is an existing function. We will simply use it.
void Paragraph_Analysis::findReplaceWord(const std::string& find, const std::string& replace)
{
    // Replace string
    modifiedString = std::regex_replace(paragraph, std::regex(find), replace);
    // Show result
    std::cout << "nnReplace '" << find << "' in original string with '"
        << replace << ". Result:nn" << modifiedString << "n";
}
// Count the frequency of letters
void Paragraph_Analysis::frequencyOfLetter()
{
    // We use a std::map. Elements that are not in the map will be created by []
    // Clear previous count
    letterCounter.clear();
    // Simply add and count all letters
    for (char c : paragraph)
        ++letterCounter[c];
    // Show result to user
    std::cout << "nnCount of all characters in text:nn";
    // Some special care must be taken for none printables. We will show this as hex values starting wit 0x
    // Iterate over all pairs consisting of letter and corresponding count
    for (const auto lc : letterCounter) {
        std::ostringstream oss;
        // Check for none printables and handle accordingly
        if (isprint(lc.first)) 
            oss << lc.first;
        else 
            oss << "0x" << std::setfill('0') << std::setw(2) << std::hex << static_cast<int>(lc.first);
        // Show final result
        std::cout << "Count of '" << oss.str() << "'    --> " << lc.second << "n";
    }
}
// Read users choice. Check for valid data
int getMenuSelection()
{
    // Show menu
    std::cout << "nnChoose an option:n   0 - Input Datan   1 - Read data from filen" <<
        "   2 - Display datan   3 - Search for wordn   4 - Search for lettern" <<
        "   5 - Count wordsn   6 - Count letters from alphabetn   7 - Find and replace a wordn" <<
        "   8 - Find and replace a lettern   9 - Frequency of lettersn   10 - Exit the programn--> ";
    // Here we will store the selection
    unsigned int selection{ 10 };
    // As long as there is no good selection, we will read a number
    bool noGoodSelection = true;
    while (noGoodSelection) {
        // Read selection. Check if valid
        noGoodSelection = (!(std::cin >> selection) || (selection > 10));
        // If not, show message and read again
        if (noGoodSelection) {
            std::cout << "Invalid Option , Try again" << 'n';
            std::cin.clear(); std::cin.ignore();
        }
    }
    return selection;
}

int main()
{
    // Instantiate our class and fill it with default data
    Paragraph_Analysis pa{ inputTestFileLong };
    // Some test code start -------------------------------------------
    // inputTestFileLong >> pa;
    //std::cout << pa;
    // pa.wordCount();
    // pa.letterCount();
    // pa.findReplaceWord(std::string("vel"), std::string("HELLO"));
    // pa.findReplaceLetter('o', '*');
    // pa.frequencyOfLetter();
    // Some test code end ---------------------------------------------
    // We will give the user to select an action
    unsigned int selection{ 0 };
    do {
        // Show the menu and get a selection from the user
        selection = getMenuSelection();
        // Depending on what the user selected
        switch (selection)
        {
        case 0:
            {   // Let the user enter data
                std::cout << "nnPlease enter data.  Type backslash '' to end input:n";
                std::string newData{}; char c;
                while (std::cin.get(c) && (c != '') && (newData.size() < MaxNumberOfCharacters))
                    newData.push_back(c);
                pa.assignNewString(newData);
                // Show new data
                std::cout << "nnNew data:nn" << pa;
            }
            break;
        case 1:
            {   // Read data from a file. Get filename, open file, then read
                std::cout << "nnRead from file: Please enter filename:n";
                std::string filename{};
                if (std::cin >> filename)
                    pa.readFromFile(filename);
                // Show new data
                std::cout << "nnNew data:nn" << pa;
            }
            break;
        case 2:  // Show data in our class rto user
            std::cout << "nnData:nn" << pa;
            break;
        case 3:
            {   // Search a word
                std::cout << "nnSearch word: Please enter word:n";
                std::string word{};
                bool wordExists{ false };
                if (std::cin >> word)
                    pa.searchWord(word);
                std::cout << "nn" << (wordExists ? "Word found" : "Word not found") << "n";
            }
            break;
        case 4:
            {   // Search a character
                std::cout << "nnSearch character: Please enter character:n";
                char character{};
                bool characterExists{ false };
                if (std::cin >> character)
                    pa.searchCharacter(character);
                std::cout << "nn" << (characterExists ? "Character found" : "Character not found") << "n";
            }
            break;
        case 5:   // Show the word count
            pa.wordCount();
            break;
        case 6:   // Show the letter count
            pa.letterCount();
            break;
        case 7:
            {   // Search and replace a word
                std::cout << "nnFind and Replace word: Please enter word to find and replace-string:n";
                std::string wordToFind{}, replaceString{};
                if (std::cin >> wordToFind >> replaceString)
                    pa.findReplaceWord(wordToFind, replaceString);
            }
            break;
        case 8:
            {   // Search and replace a charcater
                std::cout << "nnFind and Replace letter: Please enter letter to find and replace-letter:n";
                char letterToFind{}, replaceLetter{};
                if (std::cin >> letterToFind >> replaceLetter)
                    pa.findReplaceLetter(letterToFind, replaceLetter);
            }
            break;
        case 9:   // Show the frequency of all characters
            pa.frequencyOfLetter();
            break;
        case 10:   // Exit program
            std::cout << "nnLeaving program. Thank you!nn";
            break;
        default:   // Should never happen. We check anyway.
            std::cerr << "Invalid selectionn";
        }
    } while (selection != 10); // Slection 10 will end the loop
    return 0;
}