【问题标题】:using an index number, append that index (a character) to char array使用索引号,将该索引(一个字符)附加到 char 数组
【发布时间】:2021-09-14 18:17:26
【问题描述】:

我正在尝试做这样的事情。

class testClass {        
  public:              
    void testFunction(char charArray[])
    {
    char output[].append(charArray.at(1));
    char output[].append(charArray.at(7));
    char output[].append(charArray.at(3));
    cout << output;
    }


int main() {
  testClass testObject;
  testObject.testFunction("Flowers"); 
  return 0;
}
   


}

它的意思是:

  • 从索引号的 char 数组中获取字母“F”、“S”和“O”
  • 将该字符附加到输出字符数组

自从我从字符串到 *chars 和 char 数组以来,这一直令人沮丧。

不太确定最简单的解决方案是什么。 是的,我想从该字符串中一次保留 1 个字符。 这只是一个有趣的项目,但它比我想象的要复杂得多


预期输出:

  • FSO

【问题讨论】:

  • char 的数组没有std::string 中包含的功能。 char 数组唯一能做的就是设置单个元素。
  • 自从我从字符串到 *chars 和 char 数组以来,我一直很沮丧。 是的,是的,你为什么这样做?
  • 缩进可以帮助你。它说明了很多。

标签: c++ arrays c++11 char


【解决方案1】:

你的意思是这样的:

#include <string>
#include <iostream>

class testClass {        
  public:              
    void testFunction(const std::string& charArray)
    {
    std::string output;
    output.push_back(charArray.at(0));
    output.push_back(charArray.at(6));
    output.push_back(charArray.at(2));
    std::cout << output;
    }
};

int main() {
  testClass testObject;
  testObject.testFunction("Flowers"); 
  return 0;
}
   

当然,C++ 像任何理智的语言一样使用从零开始的索引。

【讨论】:

  • 谢谢你,我正为此烦恼。 :/ string& 与 string 有什么不同?它是某种类型的指针吗?
  • 没问题,如果你需要,我可以更详细地解释一些部分,或者如果有什么特别的东西让你绊倒了。
  • @TedLyngmo 我还不能。但我也要去。
  • @Quimby 我不确定 string& 的确切含义。它是某种类型的指针吗?
  • @Introverb 它是对字符串的引用,是的,它类似于指针。查看答案,例如here。它在这里用于防止对字符串参数进行额外的复制,因为默认情况下所有参数都被复制/移动,C++ 没有像 Java 这样的类的隐式引用语义。如果您正在学习 C++,我可以推荐一个精选的 list of recommended books
猜你喜欢
  • 2021-12-08
  • 2013-07-31
  • 1970-01-01
  • 2016-05-23
  • 1970-01-01
  • 1970-01-01
  • 2011-08-23
  • 2015-09-21
  • 1970-01-01
相关资源
最近更新 更多