-2

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

EG:字符串看起来像这样

Sony <TAB>         A Hindi channel.

我需要存储Sony在一个变量说char a[6];A Hindi Channel另一个变量说char b[20];

怎么能做到这一点?

4

3 回答 3

1

为许多编程语言标记字符串: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:如何在 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;
  }
}
于 2013-10-10T08:31:32.527 回答
1

可能strtok功能是您正在寻找

于 2013-10-10T07:54:08.997 回答
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;
}

未经测试,但原则是存在的

于 2013-10-10T08:16:27.690 回答