【问题标题】:c++ cstring, Is there any way to get single char from cstring?c++ cstring,有没有办法从 cstring 中获取单个字符?
【发布时间】:2021-11-18 18:54:48
【问题描述】:
char cstri[] = "hello world";

从这里,有什么方法可以从这个cstring中获取一个字符,比如第一个e,位置在1?

我尝试了几次,每次都返回从传递的索引开始的整个字符串。所以,如果我想要 'e',位置为 1,它会返回 ello world 而不仅仅是 e

我还尝试使用 strncpy()memcpy() 从字符串中复制单个字符,但它会将字符串从索引 0 复制到 null,或者只是指定的数量。

strncpy(b, cstri , 1);

我知道 cstring 是只读的,但是没有办法从 cstring 中获取单个字符吗?

我想用printf(),所以我不能用char b = cstri[1]

【问题讨论】:

  • 对于初学者,char cstri = "hello world"; 无法编译。 "想用 printf 所以我不能用 char b = cstri[1]" 你绝对可以。有%c 用于打印单个字符。
  • @HolyBlackCat 抱歉,我在 cstri 之后忘记了 []。
  • 如果你想编写 C++ 程序,你为什么要摆弄所有这些 C 的东西?不是你不能,你不应该。 ;-)
  • "如果我想要 'e',位置为 1,它会返回 hello world 而不仅仅是 'e'。" - 那么你可能正在做 cstri + 1 当你应该做cstr[1]*(cstr + 1)。您应该考虑显示代码,如果没有,至少显示其中的一部分。我说你至少得到一个good C++ book 以了解该语言的工作原理。
  • printf("%c", cstr[1]);printf("%c", *(cstr + 1));?更好的是,std::cout << cstr[1];

标签: c++ arrays char c-strings


【解决方案1】:

您的问题已经暗示了“C++”,并且考虑到 C++ std::string 和普通 c 字符串的内存表示没有区别这一额外事实,答案很简单:只需了解 std::string 的工作原理.顺便提一句。 std::string::c_str() 然后返回你漂亮的 c 字符串。

#include <string>
#include <iostream>
int main() {
  std::string hw = "hello world";
  std::cout << hw << std::endl; // output: "hello world"
  std::cout << hw.c_str() << std::endl; // output: "hello world"
  std::cout << hw[1] << std::endl; // output: 'e'
  return 0;
}

但是std::string 的功能还有很多,看看#include &lt;iomanip&gt; 可以做什么。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-04
    • 1970-01-01
    • 1970-01-01
    • 2015-08-12
    相关资源
    最近更新 更多