字符串操作(2)

来源:互联网 发布:货运车辆调度软件 编辑:程序博客网 时间:2024/06/04 19:52

本文紧接上篇《关于字符串的操作》http://blog.csdn.net/yankai0219/article/details/6883825

采用*str++这种方式将会使对字符串的操作变得简单易懂

《字符串操作(2)》将对这个网址http://apps.hi.baidu.com/share/detail/18562293中的诸多操作进行简化更改,以加深对*str++这种方式的印象,从而在以后的学习和编程中能够事半功倍。

1.字符串拷贝

上篇《关于字符串的操作》已经列出。

2.删除字符串尾部的空格

原理:从字符串的最后一个元素(即‘\0’的前一个元素)判断,如果为空格,则继续判读前一个字符,直至所判断的不再是空格为止;这时,在非空格的下一个位置加上‘\0’。

char * DelStrRgtSpace(char *str){char *address = str;str = str + StrLen(str) - 1;//此时str指向字符串最后一个字符while( ' '== *str ){str--;}*(str + 1) = '\0';return address;}

程序如上所示,这要比
http://apps.hi.baidu.com/share/detail/18562293的操作要简单很多。

3.删除字符串头部的空格

原理:同上,只是起始位置变成了字符串的第一个元素。

char * DelStrLftSpace(char *str){while(' ' == *str){str++;}return str;}


 4.使字符串右对齐。

char * StrRgtAlign(char *str){//对字符串的操作时,一定注意长度的操作char *address = str;char * tmp;int length = StrLen(str);if (NULL ==( tmp = (char*)malloc( (length + 1) * sizeof(char) )))exit(-1);tmp = StrCpy(tmp, str); // copy str to tmptmp = DelStrRgtSpace(tmp); sprintf(str,"%*.*s",length,length,tmp); //importent.free(tmp);return address;}