/*
*字符串分割,把一个长的字符串(可能有空格),分割到一个二维字符数组中。
*并且输出
*
*时间复杂度O(N)
*注意在操作二维字符串数组时:使用“数组指针”操作能方便 int(*p)[LEN];
*
*/
*字符串分割,把一个长的字符串(可能有空格),分割到一个二维字符数组中。
*并且输出
*
*时间复杂度O(N)
*注意在操作二维字符串数组时:使用“数组指针”操作能方便 int(*p)[LEN];
*
*/
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<stdbool.h>
#define NDEBUG
#include<assert.h>
#define STR_SIZE 1000 // 输入字符串长度
#define STR_LEN 50 //分割字符串最大长度
#define STR_CNT 50 //分割字符串最大数量
int str_split(char *in_str,char (*out_str)[STR_LEN]);
bool is_space(char temp);
void str_cpy(char *src_begin,char *src_end,char *dst);
int main(void)
{
char in_str[STR_SIZE];
char out_str[STR_CNT][STR_LEN];
int i=0;
int count;
char (*out)[STR_LEN]=out_str;
gets(in_str);
count=str_split(in_str,out_str);
while(i<count)
{
printf("%s\n",out[i]);
i++;
}
return 0;
}
bool is_space(char temp)
{
if(temp==' '||temp=='\n'||temp=='\t'||temp=='\v')
return true;
else
return false;
}
//使用指针数组把二维数组传递进去方便操作
int str_split(char *in_str,char (*out_str)[STR_LEN])
{
char *temp_in_str;
int count=0;
assert(in_str!=NULL&&out_str!=NULL);
while(in_str!='\0')
{
while(is_space(*in_str))
in_str++;
if(*in_str=='\0')break;
temp_in_str=in_str;
while((*in_str!='\0')&&(!is_space(*in_str)))
{
in_str++;
}
str_cpy(temp_in_str,in_str,out_str[count++]);
}
return count;
}
void str_cpy(char *src_begin,char *src_end,char *dst)
{
assert((src_begin!=NULL)&&(src_end!=NULL)&&(dst!=NULL));
while(src_begin!=src_end)
*dst++=*src_begin++;
*dst='\0';
return;
}
程序运行结果:
[trageday@lei-yum code_test]$ gcc -o string_cat string_cat.c
/tmp/ccW8eX4y.o: In function `main':
string_cat.c:(.text+0x2d): warning: the `gets' function is dangerous and should not be used.
[trageday@lei-yum code_test]$ ./string_cat
dsdd dda grgr hth jjyjyjyjj ththt
dsdd
dda
grgr
hth
jjyjyjyjj
ththt

本文介绍了如何将长字符串分割并存储到二维字符数组中,包括实现细节与时间复杂度分析。

被折叠的 条评论
为什么被折叠?



