如何减去字符串的第一个和最后一个字母

how to subtract first and last letter of a string

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

新词的第一个字母是原词的最后一个字符 第二个字母是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) ;
}
**

你以前用过Python吗? std::string 不允许负索引。您可以混合使用 front()back()substr() 字符串方法来获取单个片段,然后使用 C++ class 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;