gpt4 book ai didi

c - C 编程中分割字符串

转载 作者:行者123 更新时间:2023-11-30 20:15:29 25 4
gpt4 key购买 nike

我需要分割一个字符串并需要存储在两个单独的变量中。该字符串包含制表符空格。所以需要将其与制表符空间分开

EG:字符串看起来像这样

Sony <TAB>         A Hindi channel.

我需要将 Sony 存储在一个变量中,例如 char a[6]; 并将 A Hindi Channel 存储在另一个变量中,例如 字符b[20];

如何做到这一点?

最佳答案

为许多编程语言标记字符串:link

在您的情况下 < tab > 是一个特殊字符,可以表示为“\t”。

如果您使用C编程语言

#include<string.h>
#include<stdio.h>
#include<stdlib.h>

int main(void) {
char *a[5];
const char *s="Sony\tA Hindi channel.";
int n=0, nn;

char *ds=strdup(s);

a[n]=strtok(ds, "\t");
while(a[n] && n<4) a[++n]=strtok(NULL, "\t");

// a[n] holds each token separated with tab

free(ds);

return 0;
}

对于不使用 boost 库的 C++:

#include <string>
#include <sstream>
#include <vector>
#include <iterator>
#include <iostream>
#include <algorithm>

int main() {
std::string s = "Sony\tA Hindi channel.";
std::vector<std::string> v;
std::istringstream buf(s);
for(std::string token; getline(buf, token, '\t'); )
v.push_back(token);
// elements of v vector holds each token
}

使用 C++ 和 boost:How to tokenize a string in C++

#include <iostream>
#include <string>
#include <boost/foreach.hpp>
#include <boost/tokenizer.hpp>

using namespace std;
using namespace boost;

int main(int, char**) {
string text = "Sony\tA Hindi channel.";

char_separator<char> sep("\t");
tokenizer< char_separator<char> > tokens(text, sep);
BOOST_FOREACH (const string& t, tokens) {
cout << t << "." << endl;
}
}

关于c - C 编程中分割字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19289982/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com