c++ - 将单个字符串分成多个字符串 C++?

标签 c++ string

我需要输入3个以逗号分隔的全名

全名 1:约翰、史密斯、弗林
全名 2:沃尔特、肯尼迪、罗伯茨
全名 3:Sam、Bass、Clinton

然后这样输出

名字 1:约翰
名字 2:沃尔特
名字 3:山姆

中间名 1:史密斯
中间名 2:肯尼迪
中间名 3:低音

姓氏 1:弗林
姓氏 2:罗伯茨
姓氏 3:克林顿

我该怎么做? 到目前为止,这是我的代码

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;

int main () {
    char first[3][100];
    char middle[3][100];
    char last[3][100];
    char full[3][100];
    int i; 

    cout << "Enter 3 Full Names <first, middle and last names separated by comma>:" << endl;
    for (i=0; i<3; i++) {
         cout << "Full Name " << i+1 << ":" ;
        gets (full[i]);          
    }

    cout << "The first names are: " << endl;
    for (i=0; i<3; i++) {
        strcpy (first[i], full[i]);
        if (strcmp (first[i], ", ")) {
            cout << "First Name "<< i+1 << ":" ;
            strcpy ( first[i], full[i] );
            cout << (first[i]);
            cout << endl;   
        }
    } 
    cout << "The middle names are: " << endl;
    for (i=0; i<3; i++) {
        cout << "Middle Name "<< i+1 << ":" ;
        cout << (middle[i]);
        cout << endl;
    }
    cout << "The last names are: " << endl;
    for (i=0; i<3; i++) {
        cout << "Last Name "<< i+1 << ":" ;
        cout << (last[i]);
        cout << endl;
    }
    system("pause");
    return 0;
}

最佳答案

我想这里你想要的是字符串类的拆分方法,该方法应该是这样的:

void SplitName(const string& fullName, const string& delims, vector<string>& names)
{
    size_t i = 0;
    size_t j = 0;
    while (i < fullName.size())
    {
        i = fullName.find_first_not_of(delims, i);
        j = fullName.find_first_of(delims, i);
        if (i < fullName.size())
        {
            names.push_back(fullName.substr(i, j - i));
        }
        i = j;
    }
}

您可以将“:”定义为delims,那么names[1]是First Name,names[2]是Middle Name,names[3]是Last Name。

关于c++ - 将单个字符串分成多个字符串 C++?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5088358/

相关文章:

c++ - 为什么有两种通过指针调用函数的方式?

c - Strcat 附加整个结构而不是一个元素

arrays - 赋值左侧的函数调用必须返回 Variant 或 Object,在两个数组中查找公共(public)值

java - 搜索大字符串以查看是否存在无效的 "parameter"

c++ - 重载模板运算符*

c++ - 模板函数的实例化点在调用点之后,编译器如何查找和链接它?

c++ - 关于引用类型复制初始化的问题

c++ - QT UI 测试的最佳方法

javascript - 正则表达式 - 用打开和关闭标记替换备用特殊字符

python - 切片列表中的所有字符串?