字符串分割到二维字符数组中:

/*
 *字符串分割,把一个长的字符串(可能有空格),分割到一个二维字符数组中。
 *并且输出
 *
 *时间复杂度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



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值