Chinaunix首页 | 论坛 | 博客
  • 博客访问: 405938
  • 博文数量: 21
  • 博客积分: 5030
  • 博客等级: 大校
  • 技术积分: 1275
  • 用 户 组: 普通用户
  • 注册时间: 2006-06-16 09:18
文章分类
文章存档

2012年(1)

2011年(6)

2010年(2)

2009年(1)

2008年(11)

我的朋友

分类:

2008-08-23 16:32:35

题目:将字符串中所有多于2个的空格变为1个空格
解答:C语言版本,我自己写的,多用了些内存,但是不用考虑那么多状态。:)
 

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

char text[]="  I  love  Linux    hehe ";

int main(int argc, char **argv)
{
    int begin=0;
    int end = 0;
    char *p0 = (char *)malloc(sizeof(text)),*p1;
    int i,len=strlen(text);

    if(text[0] == ' ') begin=1;
    if(text[len-1] == ' ') end = 1;

    printf("Before converting...\n%s*\n",text);
    memset(p0,'\0',sizeof(p0));
    if(begin)
    {
        p0[0]='\0';
        strcat(p0," ");
    }
    
    for(i=0; i<len; i++)
    {
        if(text[i]==' ')
        {
            text[i]='\0';
        }else
        {
            p1 = &text[i];
            while(text[i] != ' ')
                i++;//越过所有非空格

            text[i]='\0';
            strcat(p0,p1);
            strcat(p0," ");
        }
    }
    if(!end)
        p0[strlen(p0)-1]='\0';

    printf("After converting...\n%s*\n",p0);
    free(p0);

    return 0;
}

Perl语言版本:

 

#!/usr/bin/perl

use strict;
use warnings;

my $str = " I love Linux hehe ";
print "Before converting...\n".$str."*\n";

$str =~ s/\ +/ /g;
print "After converting...\n".$str."*\n";

阅读(1191) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

chinaunix网友2008-09-05 17:03:15

为什么不把tab也考虑进去呢。。。。