【问题标题】:Changing first and last letter of a 6 letter word in C++ [closed]在 C++ 中更改 6 个字母单词的第一个和最后一个字母 [关闭]
【发布时间】:2020-09-28 07:51:00
【问题描述】:

有没有其他方法可以改变6个字母单词的第一个字母和最后一个字母?

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string word;
    cout<< "\nEnter a 6 letter word or numbers: ";
    cin>>word;
    word[0]++;
    word[5]++;
    cout << "Result: " << word << endl;

    return 0;
}

【问题讨论】:

  • 什么意思?是的,还有其他方法。你现在的使用方式有什么问题?
  • 有人建议我使用 if/else 或 setw,这可能吗?
  • @idclev463035818 我需要 2-3 种方法。这是我想到的最简单的一个。
  • 嗯,对于初学者,您可以使用if 来检查单词是否已被实际阅读以及是否至少包含 6 个字母。你已经被介绍给迭代器了吗? std::string的成员函数你知道多少?
  • 您能说明一下您要达到的目标吗?

标签: c++


【解决方案1】:

您也可以使用string::replace,但与使用下标运算符替换相比,这是一种相当迂回的方式。

类似

#include <iostream>
#include <string>
using namespace std;

    int main()
    {
        string word;
        cout<< "\nEnter a 6 letter word or numbers: ";
        cin>>word;
        cout<<word;

        string repl = "x";
        word.replace(5,1, repl);      //replace the 5th position with 1 
                                              //character using string repl

        cout << "Result: " << word << endl;
    
        return 0;
    }

看看http://cplusplus.com/reference/string/string/replace/

C++, best way to change a string at a particular index

How to replace one char by another using std::string in C++?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-07
    • 2017-02-13
    • 2017-01-25
    • 1970-01-01
    • 2020-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多