首页 > 其他 > 详细

将字符串中的单词分割,存入二维数组后输出

时间:2014-08-24 12:54:32      阅读:356      评论:0      收藏:0      [点我收藏+]

思路

每次内部循环需要找到一个单词,将其存入数组。外循环遍历至字符串末尾结束。

代码

/*************************************************************************
    > File Name: word_split.c
    > Author: KrisChou
    > Mail:zhoujx0219@163.com 
    > Created Time: Sun 24 Aug 2014 10:42:48 AM CST
 ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 128
#define WORD_CNT 128
#define WORD_LEN 256

static int my_isspace(char c)
{
    if(c ==   || c == \n || c == \t || c == \v)
        return 1;
    else
        return 0;
}

static void show(char(*words)[WORD_LEN],int cnt)
{
    int index;
    for(index = 0; index < cnt; index++)
    {
        printf("%15s",words[index]);
    }
}

static void word_save(char *line, int bg, int end, char *dest)
{
    int index,index_dest;
    for(index = bg,index_dest = 0; index <= end;index++,index_dest++ )
    {
        dest[index_dest] = line[index];
    }
    dest[index_dest] = \0;
}

static int word_split(char *line,char(*words)[WORD_LEN])
{
    int bg,end;
    int word_cnt;
    bg = 0;
    word_cnt = 0;
    while(line[bg] != \0)
    {
        while(my_isspace(line[bg]))
        {
            bg++;
        }
        if(line[bg] == \0)
        {
            break;
        }
        end = bg;
        while(line[end] != \0 && !my_isspace(line[end]))
        {
            end++;
        }
        word_save(line,bg,end-1,words[word_cnt++]);
        bg = end;
    }
    return word_cnt;
}

int main(int argc, char *argv[])
{
    int cnt;
    char line[N];
    char words[WORD_CNT][WORD_LEN];
    while(fflush(stdin),gets(line) != NULL)
    {
        cnt = word_split(line,words);
        show(words,cnt);
        printf("\n");
    }
    return 0;
}

将字符串中的单词分割,存入二维数组后输出

原文:http://www.cnblogs.com/jianxinzhou/p/3932682.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!