【问题标题】:How to get the first letter from a string in a linked list?如何从链表中的字符串中获取第一个字母?
【发布时间】:2017-11-06 14:21:09
【问题描述】:

我试图从substr(0,1) 的名称(类型字符串)中获取第一个字母。但是,我想要一个指向它的指针,在单个链表中。

所以我这样写:h->name.substr(0,1) 其中 (h) 是指针,(name) 是结构体中的字符串类型。

struct empType{
    string name;
    empType *next;
};

但是当我打印h->name.substr(0,1) 时,它显示为(NULL)。

假设链表存在,(h)是指向第一个节点的指针。

【问题讨论】:

  • 为什么不h->name[0]
  • @CoryKramer 成功了,谢谢。我以前不知道这种方法。
  • h->name.data() 将为您提供指向第一个字母的指针。
  • @Ctx 它给了我一个语法错误,说表达式必须是一个可修改的左值

标签: c++ string pointers character


【解决方案1】:

要获得(对a的引用)第一个字符,请使用std::basic_string::front成员函数:

h->name.front();

std::basic_string::at,值为0

h->name.at(0);

或索引为0std::basic_string::operator[] 运算符:

h->name[0];

或取消引用std::basic_string::data 指针:

*h->name.data();

或取消引用 std::basic_string::begin 迭代器:

*h->name.begin();

包含您的结构的简单示例:

#include <iostream>
#include <string>
struct empType{
    std::string name;
    empType *next;
};

int main() {
    empType* h = new empType;
    h->name = "Hello World";
    h->next = nullptr;
    std::cout << h->name.front();
    std::cout << h->name.at(0);
    std::cout << h->name[0];
    std::cout << *h->name.data();
    std::cout << *h->name.begin();
    delete h;
}

【讨论】:

    猜你喜欢
    • 2018-07-11
    • 1970-01-01
    • 2016-06-03
    • 1970-01-01
    • 1970-01-01
    • 2013-10-29
    • 1970-01-01
    • 2019-01-16
    • 2019-09-10
    相关资源
    最近更新 更多