我需要拆分一个字符串,需要存储两个单独的变量。该字符串包含制表符空间。所以它需要与标签空间分开
EG:字符串看起来像这样
Sony <TAB> A Hindi channel.
我需要将Sony
存储在一个变量中,如char a[6];
和A Hindi Channel
存储在另一个变量中char b[20];
怎么做呢?
答案 0 :(得分:1)
strtok功能可能就是你正在寻找
答案 1 :(得分:1)
许多编程语言的标记字符串:link
在你的情况下&lt;标签&gt;是一个特殊字符,可以表示为'\ 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;
}
}
答案 2 :(得分:0)
我的C已经老了,但是这样的事情应该有效:
#include <stdio.h>
int getTabPosition (char str [])
{
int i = 0;
//While we didn t get out of the string
while (i < strlen(str))
{
//Check if we get TAB
if (str[i] == '\t')
//return it s position
return i;
i = i + 1;
}
//If we get out of the string, return the error
return -1;
}
int main () {
int n = 0;
//Source
char str [50] = "";
//First string of the output
char out1 [50] = "";
//Second string of the output
char out2 [50] = "";
scanf(str, "%s");
n = getTabPosition(str);
if (n == -1)
return -1;
//Copy the first part of the string
strncpy(str, out1, n);
//Copy from the end of out1 in str to the end of str
//str[n + 1] to skip the tab
memcpy(str[n+1], out2, strlen(str) - n);
fprintf(stdout, "Original: %s\nout1=%s\nout2=%s", str, out1, out2);
return 0;
}
未经测试,但原则是