简体   繁体   中英

String manipulation C++

I need to make some functions but i don't know how.

  1. join two strings, input positions and output the characters from the position in the string

Example: s1=first, s2=second; s1+s2=firstsecond, pos=3,7,10, output=ren

this is my code for one postion, but i don't know how to make for several position, main problem is how to limit input of position:

s=s1+s2;
cin>>pos;
cout<<s[pos-1];
  1. define vowel in string and replace that vowel with string

Example: s=firstsecondthird, vowel=i, str=EXA, output=fEXArstsecondthEXArd

This is what i know, i don't know how to make the replacing vowel with string(str)

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

Thank you

Catch! :)

#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;
}

If to enter

first
second
3 7 10 0
i

then the program output will be

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

You can use it as a template for your great program.:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM