如何从输入字符串中提取特定位置的字符?

How do I extract characters in a specific position from an input string?

本文关键字:位置 定位 字符 提取 输入 字符串      更新时间:2023-10-16

对于我的家庭作业项目,我应该创建一个程序,询问用户他们最喜欢的城市以及他们想要显示哪个角色。用户输入一个数字,表示他们想要显示的城市中字符的位置,程序应该在此位置显示字母。

我们还没有学会如何从字符串中提取字符,但我们项目的这一部分应该表明我们可以正确地谷歌来找到我们的编码解决方案。我找到了一个 void 函数,可以为我从特定位置提取角色,但完全不知道如何使用它。我已经尝试了几种不同的方法,并输入了我可能想到的所有方法来实现此功能,但它没有奏效。

我尝试完全按原样复制我在网上找到的示例代码(在此地址找到的第一个示例:https://www.geeksforgeeks.org/string-at-in-cpp/(,但即使是该示例也无法在 Visual Studio 2017 中运行。

#include <iostream>
#include <string>
using namespace std;
void at(string);
int main()
{
//variables for favorite city & display character
string favCity;
int dispChar;
//asking user for favorite city
cout << "Input your favorite city: ";
cin >> favCity;
cout << "Which character would you like to display: ";
cin >> dispChar;
cout << endl << endl;
cout << "The user entered: " << favCity << endl;
cout << "The character at position " << dispChar << " is: " << at();
}

预期结果是计算机将显示"位置 (dispChar( 处的字符为:(无论用户输入位置 dispChar 处的任何字母(">

例如:"The character at position 2 is: e//如果用户输入城市底特律

我收到错误at未定义,当我尝试使用str.at();时,我会得到str未定义,等等。

无需使用外部函数即可通过索引从字符串中提取字符。std::string本身实现了std::string::at函数,也重载了[]运算符。

所以有两种方法可以做到这一点:

1.

cout << "The character at position " << dispChar << " is: " << favCity.at(dispChar);

阿拉伯数字。

cout << "The character at position " << dispChar << " is: " << favCity[dispChar];

std::string::at 可用于从给定字符串中提取字符。char& string::at (size_type idx)

字符串::at 函数返回特定位置 (idx( 处的字符。您可以直接使用 string::at 作为包含类的。在此处了解更多信息

因此,在您的解决方案中,您声明了void at(string);因此您也需要定义它。 我已经对您的代码进行了一些更改,我认为应该这样做。

#include <string>
using namespace std;
void extract_char(string str, int pos)
{
cout<<str.at(pos);
}
int main(void)
{
int dispChar;
string favCity;
cout<<"Input your favorite city: ";
cin>>favCity;
cout<<"Which position would you like to extract the character from(0 to size of city): ";
cin>>dispChar;
cout<<endl<<endl;
cout<<"The user entered: "<<favCity<<endl;
extract_char(favCity, dispChar-1);
/*
OR
cout<<"The character at position "<<dispChar<<" is: "<<favCity.at(dispChar-1);
*/
return 0;
}