【问题标题】:how to subtract first and last letter of a string如何减去字符串的第一个和最后一个字母
【发布时间】:2018-07-21 12:48:45
【问题描述】:

首先,我是编程新手。 我被要求创建一个程序,提示用户插入一个单词,然后我将它翻译成某种假语言。 所以我做了以下:

新词的firstLetter是原词的最后一个字符 secondLetter 是 ncy thirdLetter 是输入的单词,没有第一个和最后一个字符 第四个字母是nan 第五个字母是单词的第一个字符

例如用户输入=狗 新词是:gncyonand

我的代码是这样的,但它失败了,我认为是因为字符串还不存在(用户仍然必须插入它)。请帮忙:

**

#include <iostream> //for cin and cout
#include <string> //for string data

using namespace std;
int main()

{
    //I add a welcome message:
    std::cout << "*************************************************\n"
    << " Welcome to Nacy-latin converter program\n"
    << "*************************************************\n\n";


    // I declare first string:
    std:: string userWord; //the word the user imputs
    std::string firstLetter= userWord.substr(-1,0); //last char of the entered word
    std::string secondLetter = "ncy";
    std::string thirdLetter= userWord.substr(1, userWord.length() - 1); //last char of the entered word
    std::string fourthLetter = "nan"; //just nan
    std::string fifthLetter= userWord.substr(0,1); ; //the first char of the userWord


    //I ask the user to imput data:
    cout << "Hey there!";
    cout << endl<<endl;
    cout << "Please enter a word with at least two letters and I will converted into Nacy-latin for you:\n";


  //return data to the user:
    cout<<"The word in Nancy-Latin is:" <<firstLetter << secondLetter << thirdLetter <<fourthLetter <<fifthLetter<<'\n';


    // Farewell message
    cout << "\nThank you for the 'Nancy-latin' converter tool!\n";
    // system(“pause”);

    return (0) ;
}
**

【问题讨论】:

  • std::string 具有 front() and back() 函数,用于获取第一个和最后一个字符。但当然要等到输入可用。

标签: c++ arrays string substr


【解决方案1】:

你以前用过 Python 吗? std::string 不允许负索引。您可以混合使用 front()back()substr() 字符串方法来获取单个片段,然后使用 C++ 类 std::stringstream 构建新字符串。

std::stringstream ss;
ss << userWord.back() << "ncy";
ss << userWord.substr(1, userWord.size() - 2);
ss << "nan" << userWord.front();
std::cout << ss.str();

不要忘记检查用户输入的至少两个字符。

替换成新词。

std::swap(userWord.front(), userWord.back());
userWord.insert(1, "ncy");
userWord.insert(userWord.size() - 2, "nan");
std::cout << userWord;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-16
    • 2013-06-17
    • 1970-01-01
    • 2019-09-10
    • 1970-01-01
    • 1970-01-01
    • 2016-10-16
    • 1970-01-01
    相关资源
    最近更新 更多