【问题标题】:Creating string literals创建字符串文字
【发布时间】:2019-10-08 06:39:27
【问题描述】:

我有一个字符串数组。我想获取该数组中的第 n 个单词,并打印如下输出:

输入:government 输出:g8t

基本上:first letter + total number of letters-2 + last letter

输出也存储在字符串数组中。 这是我尝试过的基本代码:

out[j]=in[j].at(0) + (n-2) + in[j].at(n-1);
//n is the length of word , used str.length() for that

这里有什么问题?

【问题讨论】:

  • 请至少标记您使用的语言。
  • 抱歉,忘记添加语言了。

标签: arrays string c++14


【解决方案1】:

注意这一点to_string!!!

一个小试验:

#include<iostream>
#include<string>
#include<vector>

using namespace std;

int main() {

vector<string> words;
string input;
int count = 0;
cout << "Enter 5 words :";

while (cin >> input) 
{
    words.push_back(input);
    if (++count > 4)
        break;
}

for (int i = 0; i < words.size(); i++) {
    string str;
    int size = words.at(i).length();
    str = words.at(i).at(0) + to_string(size) + words.at(i).at(size - 1);
    cout << str + "\n";
}

cin>> input;
return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-19
    • 2014-05-27
    • 1970-01-01
    • 2019-09-29
    • 1970-01-01
    • 2012-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多