题目:将字符串中所有多于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) |