EverSpring working shop

To pursue creative ideas based on nature.

统计

留言簿(1)

他山之石

阅读排行榜

评论排行榜

Code Snippet: Trim the unnecessary white space in a sentence.

This code snippet is trying to trim the unnecessary white space in a sentence to use only one white space between each word.
The key idea of this code is move the rest of the string to the place just after the white space found each time.
QUITE simple but useful code snippet.

Running Enviroment: Visual C++ 2005 Express edition.

 1// string_trim.cpp : Defines the entry point for the console application.
 2//
 3
 4#include "stdafx.h"
 5#include "string.h"
 6
 7/* The Modifications are Made to the Same String */
 8void inside_trim(char* x)
 9{
10        unsigned int i,pos,nxtchar;
11 
12        for(i=0;i<strlen(x);i++)
13        {
14                if( x[i] == ' ' )
15                {
16                        pos=i+1;
17                        nxtchar=pos-1;
18                        while(x[nxtchar++== ' '){}
19 
20                        strcpy(&x[pos],&x[nxtchar-1]);  // move forward the rest of the whole string!
21                        printf("\n%s",x);
22                }
23        }
24}
25
26
27int _tmain(int argc, _TCHAR* argv[])
28{
29        char xyz[]="Does      this     work?";
30        printf("\n%s",xyz);
31        inside_trim(&xyz[0]);
32        printf("\n%s",xyz);
33    
34    return 0;
35}
36
37

Running Result:


posted on 2007-10-12 21:58 everspring79 阅读(208) 评论(0)  编辑 收藏 引用 所属分类: Snippet


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理