434. Number of Segments in a String

来源:互联网 发布:网络大电影编剧价格 编辑:程序博客网 时间:2024/06/06 01:24

题目:

Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters.

Please note that the string does not contain any non-printable characters.

Example:

Input: "Hello, my name is John"Output: 5
stoke函数使用,返回为 char*,参数列表,第一个为待分割的的char* 第一次写了之后后面可以置为NULL,自动分割剩下的字符串,第二个为分割的字符符号。

string 转char*

1.一种是string s,s.c_str();char *p=str.c_str();

2.第二种是    !!!!!!!

string str="abc";
char *p=str.data();%这行应更正为char*p=(char*)str.data();,引自贴内网友的回复

3.

3. copy
比如
string str="hello";
char p[40];
str.copy(p,
5,0); //这里5,代表复制几个字符,0代表复制的位置
*(p+5)='\0'; //要手动加上结束符

class Solution {public:    int countSegments(string s) {        char * m =(char*)s.data();        int count = 0;        const char * split = " ";         char * p;         p = strtok(m,split);         while(p!=NULL) {            count++;           p = strtok(NULL,split);        }         return count;    }};