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

时间:2018-02-11 03:34:18

标签: c++ arrays string substr

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

新单词的firstLetter是原始单词的最后一个字符 secondLetter是ncy thirdLetter是输入的单词,没有第一个和最后一个char 第四封信是南 fifthLetter是单词

的第一个字符

e.g。用户输入=狗 新词是: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) ;
}
**

1 个答案:

答案 0 :(得分:0)

你之前使用过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;