gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 02:21:50 26 4
gpt4 key购买 nike

我需要做一些功能,但我不知道怎么做。

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

例子:s1=第一,s2=第二; s1+s2=firstsecond, pos=3,7,10, output=ren

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

s=s1+s2;
cin>>pos;
cout<<s[pos-1];
  1. 在字符串中定义元音并用字符串替换该元音

例子:s=firstsecondthird, vowel=i, str=EXA, output=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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com