如何在 C++ 中解析带分隔符的字符串?

问题描述 投票:0回答:2

这花了我很长时间才弄清楚,我研究了很多不同的例子,但有些看起来很复杂,并且出于 A、B、C 的原因,其中有额外的步骤......这就是我需要的 - 让我们说你有一个字符串,我们将其称为字符串 A

字符串 A =“我

所以分隔符当然是 '<'

如何解析这个字符串以取出分隔符?然后我必须创建这些字符串的对象并将它们添加到指针数组中。

请参阅下面的示例:) 请忽略顶部的所有指令。我讨厌猜测我需要什么和不需要什么,所以我开始在所有文件中包含我需要的每一个文件(除了在其他文件中包含文件)。我花了 6 个多小时研究解析,但一无所获,所以我今晚正式结束了......

我猜我也对指针感到困惑,因为我认为下面的行将是一个指针,用于从学生头文件中的 Student 类获取数据,并让它创建一个指针数组,然后我将使用该指针填充对象下面的“add”方法........但它告诉我-无法使用“string *”类型的右值(又名“basic_string *”)初始化类型为“Student *”的成员子对象....在尝试学习这些材料时,我感觉自己向前迈出了一步,然后撞到了墙上,然后又弹回了两步......

Student* classRosterArray = new string[5];
#pragma once
#include <stdio.h>
#include <string>
#include <iostream>
#include <print>
#include <iomanip>
#include "student.hpp"
using namespace std;

class Roster
{
private:
    // Array of pointers, size = 5-- I thought I was supposed to use a pointer to reference the Student class.... and call the new array which we are adding objects into classRosterArray?
    Student* classRosterArray = new string[5];
    //string* classRosterArray = new string[5]; --Is this what is needed??
    
public:
    void parse(string row);
    void add(string studentId,
             string firstName,
             string lastName,
             string emailAddress,
             int age,
             int daysToComp3Course,
             DegreeProgram degreeProgram);
};
c++ arrays object parsing delimiter
2个回答
0
投票

如何解析这个字符串以取出分隔符?

要提取每个单词,请使用 std::getlinestd::istringstream:

#include <string>
#include <sstream>
#include <iostream>

int main()
{
    std::string A = "I<Like<Butterscotch<candies<so<much";
    std::istringstream strm(A);
    std::string word;
    while (std::getline(strm, word, '<'))
        std::cout << word << "\n";
}

输出:

I
Like
Butterscotch
candies
so
much

0
投票

我确信有一些奇特的STL方法可以做到这一点,但坦率地说,这正是C标准库中的strtok(),我只是使用它,除了在本世纪,我会使用strtok_r,以免打破多线程。如果您使用的是 Windows,那么您就可以忍受所提供的内容。

https://man7.org/linux/man-pages/man3/strtok.3.html

https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/strtok-strtok-l-wcstok-wcstok-l-mbstok-mbstok-l?view=msvc-170

您还可以使用 strchr() 执行类似的操作来定位字符串中字符的第一次出现。更好的是,还有 strsep(),它可以同时管理多个分隔符,被设计为 strtok 的替代品,以更好地处理它的许多缺点。

如果您在现实世界中尝试处理 unicode 或从右到左的文本系统,事情会变得更有趣,但我想我会寻找更多特定于操作系统的解决方案,例如 [NSString enumerateSubstringsInRange:options:usingBlock:] 。这个特殊问题看起来像是某人的作业。

© www.soinside.com 2019 - 2024. All rights reserved.