c++ - 字符串操作 C++

标签 c++ string

我需要制作一些功能,但我不知道如何做。

  1. 连接两个字符串,输入位置并输出字符串中该位置的字符

示例:s1=第一个,s2=第二个; s1+s2=第一第二,pos=3,7,10,输出=ren

这是我针对一个职位的代码,但我不知道如何制作多个职位,主要问题是如何限制职位的输入:

s=s1+s2;
cin>>pos;
cout<<s[pos-1];
  • 在字符串中定义元音并用字符串替换该元音
  • 示例:s=firstsecondthird、元音=i、str=EXA、输出=fEXArstsecondthEXArd

    这就是我所知道的,我不知道如何用 string(str) 替换元音

    cin>>vowel;
    if(check is defined character vowel)
    {
       cin>>str;
       .
       .
       .
    }
    

    谢谢

    最佳答案

    捕获! :)

    #include <iostream>
    #include <string>
    #include <cstring>
    
    int main() 
    {
        std::cout << "Enter first string: ";
    
        std::string s1;
        std::cin >> s1;
    
        std::cout << "Enter second string: ";
    
        std::string s2;
        std::cin >> s2;
    
        s1 += s2;
    
        std::cout << "The joined string is " << s1 << std::endl;
    
        std::cout << "Enter several positions in the joined string (0-stop): ";
    
        std::string s3;
        std::string::size_type pos;
    
        while ( std::cin >> pos && pos != 0 )
        {
            if ( --pos < s1.size() ) s3 += s1[pos];
        }
    
        std::cout << "You have selected the following letters " << s3 << std::endl;
    
        const char *vowels = "aeiou";
        char c;
    
        do
        {
            c = '\0';
            std::cout << "Enter a vowel: ";
        } while ( std::cin >> c && !std::strchr( vowels, c ) );
    
        if ( c != '\0' )
        {
            for ( auto pos = s1.find( c, 0 ); 
                  pos != std::string::npos; 
                  pos = s1.find( c, pos ) )
            {
                const char *t = "EXA";
                const size_t n = 3;
    
                s1.replace( pos, 1, t );
                pos += n;
            }
    
            std::cout << "Now the joined string looks like " << s1 << std::endl;
        }       
    
        return 0;
    }
    

    如果输入

    first
    second
    3 7 10 0
    i
    

    那么程序输出将是

    Enter first string: first
    Enter second string: second
    The joined string is firstsecond
    Enter several positions in the joined string (0-stop): 3 7 10 0
    You have selected the following letters ren
    Enter a vowel: i
    Now the joined string looks like fEXArstsecond
    

    您可以将其用作您出色的程序的模板。:)

    关于c++ - 字符串操作 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30966736/

    相关文章:

    java - 从后面搜索时如何从字符串的一部分中获取子字符串

    python - 使用 Python Pandas 将列值与不同列进行比较,并返回同一行但不同列的值

    c++ - 基于模板参数的条件编译时包含/排除代码?

    c++ - 为什么调用 `int* Get()` 而不是 `const int& Get()` ?

    C++ 指向 unordered_map 条目的指针发生变化,但条目没有

    Python - 连接多个子文件夹中的文本文件

    c# - 文件路径作为命令行参数

    c - 在不创建新文件的情况下查找并替换文本文件中的特定字符串

    c++ - 通过内容访问 QVector 元素索引

    c++ - add_lvalue_reference 有什么作用?