现在的位置: 首页 > 综合 > 正文

c++里面的字符数组和字符串及其分割

2017年08月18日 ⁄ 综合 ⁄ 共 1925字 ⁄ 字号 评论关闭

做了一道题,又在输入上耗费时间,真是让人恼火,不管怎么着,都是自己基础不牢固的缘由,那就得拿出时间来复习巩固扎实,自作孽自己受,不受就得着不可活吧!!

1、结构体声明动态数组,按照平常的来就好了。

2、结构体声明变量,Node, *Link ,指针或者直接一个节点

3、字符数组初始化的时候,一定是在初始化时候定义,或者一个个字节去赋值,否则不能单独拿变量去赋值或者整体赋值,结构体里面更是如此!!所以感觉结构体里面声明字符之类的东西还是用string好了。

4、结构体数组还是别用动态声明,new还是malloc 都麻烦,直接用vector好了!!

6、分割问题

我要怒了,java里面明明一个split就搞定的事情结果在这里却搞了好久,真心恼火,不过这次是真的非常清楚了字符数组和字符串直接的关系及其相应的操作,即使是自己封装一个函数,应该也没问题了,现在讲有的方法讲解如下:

1)利用strtok()  

不过这个函数好像存在什么线程问题,所以还有一个strtok_r() 方法

char temp[71];
string state= "I am a student"
		strcpy(temp,state.c_str());//
		char *p;// 这里p 不能是string 
		p = strtok(temp," ");
		states.push_back(p);
		while(p)//这里不能是string的原因是,char数组最后一个是空字符为null,而string 是没有的
		{
			cout<<p<<endl;
			states.push_back(p);
			p = strtok(NULL," ");//先输出,因为最后一个是空的
			
//这个是摘自其他人的//借助strtok实现split,分割符号其实可以是多个
#include <string.h>
#include <stdio.h>

int main()
{
        char s[] = "Golden Global      View,disk * desk";
        const char *d = " ,*";
        char *p;
        p = strtok(s,d);
        while(p)
        {
                printf("%s\n",p);
                p=strtok(NULL,d);
        }

        return 0;
}

2)自己来写,一个个判断空格,利用stcpy()函数和find()函数,下面是分割“-” 

    String recogScop = "01-02-03";
    cout<<recogScop<<endl;
    int size = recogScop.size();
    int pos = 0;
    string result[20] ;

    for(int i=0, j=0; i<size; i++,j++ )
    {
        pos = recogScop.find("-", i);

        if(pos == -1)
        {
           String subEnd = recogScop.substr(i, size - i); //最后一个字符串
            result[j] = subEnd;
            break;
        }
        if(pos >0)
        {
            String sub = recogScop.substr(i, pos-i);
            result[j] = sub;
            i = pos;
        }
    }

    for(int i=0; result[i] != ""; i++)
        cout<<result[i]<<endl;	

3)号称是最优雅的分割,其实就是一句话的事,还不太理解

标准库中有个方法可以做到:
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>
using namespace std;

int main()


{

	string sentence = "And I feel fine...";
	istringstream iss(sentence);
	copy(istream_iterator<string>(iss),istream_iterator<string>(),ostream_iterator<string>(cout, "\n"));
}
若不拷贝被拆分的字符串到一个输出流中,可以用通用的泛型拷贝算法把他们插入到一个容器中。
vector<string> tokens;
copy(istream_iterator<string>(iss),istream_iterator<string>(),back_inserter<vector<string> >(tokens));

另外若是使用boost库可以有如下解决方法:
#include <boost/algorithm/string.hpp>
std::vector<std::string> strs;
boost::split(strs, "string to split", boost::is_any_of("\t "));

抱歉!评论已关闭.