去除字符串中多余的空格 C语言实现
来源:互联网 发布:知敬畏 编辑:程序博客网 时间:2024/05/10 06:30
比如“hello world hey baby”
变成“hello world hey baby”
思想是设置两个指针,前面的(front)一直往前走直到字符串结尾,后面的(last)复制front当前指向的字符,
当遇到多个空格时并不复制,而是等到front指向非空格字符时在往前走。
#include <stdio.h>
#include <stdlib.h>#include <string.h>
void omitSpace(char *str){
char *front = str;
char *last = str;
if(str == NULL) return;
while((*front) == ' ') {++front;} //omit space in the beginning
while((*front) != '\0'){
if((*front) == ' '){
*last = ' ';
while((*front) == ' '){
++front;
}
}else{
*last = *front; //can also add one if condition to avoid unnecessary assignment: if(last != front){*last = *front;}
++front;
}
++last; //front has pointed to the next char, so don't ++front;
}
*last = '\0';
}
int main(){
char *cases[] = {"hello world!!!", " hello world...", " Hello world???", "he llo wor ld ... "};
char **str;
int strIndex = 0;
int letterIndex = 0;
int casesNum = sizeof(cases) / sizeof(char*); //don't forget to be divided by sizeof(char*).
str = (char**)malloc(sizeof(cases));
for(strIndex = 0; strIndex < casesNum; ++strIndex){
str[strIndex] = (char*)malloc(1 + strlen(cases[strIndex]));
for (letterIndex = 0; letterIndex < strlen(cases[strIndex]); ++letterIndex)
{
str[strIndex][letterIndex] = cases[strIndex][letterIndex];
}
str[strIndex][letterIndex] = '\0';
}
for(strIndex = 0; strIndex < casesNum; ++strIndex){
printf("%s\n", str[strIndex]);
omitSpace(str[strIndex]);
printf("%s\n", str[strIndex]);
}
for(strIndex = 0; strIndex < casesNum; ++strIndex){
free(str[strIndex]);
}
free(str);
return 0;
}
- 去除字符串中多余的空格 C语言实现
- C语言实现一个去除字符串中的首尾空格,字母中间有多个空格的去除多余的,剩余一个空格
- C语言实现去除字符串中空格
- C语言实现去除字符串中空格
- C语言实现去除字符串中空格
- 去除字符串中多余的空格
- C++去除字符串中多余的空格
- 去除字符串多余的空格
- 去除字符串末尾的空格的C语言实现
- 去除字符串中的空格 C语言实现
- 编写一个函数用于去除字符串中多余的空格,,
- Qt中去除QString字符串里面多余的空格
- H面试程序3:去除字符串中多余的空格
- Java 去除字符串中多余的空格,只留一个
- java 去除字符串中多余的空格,只留一个
- 字符串去除多余空格
- 字符串去除多余空格
- 提高项目30.7-去除句子中所有多余的空格,返回去除了空格的字符串
- 矩阵乘法求解
- Emacs和Vim:神的编辑器和编辑器之神
- 程序语言与程序员的快乐
- 使用debugger在dojo小部件中调试代码
- 12个有趣的C语言面试题
- 去除字符串中多余的空格 C语言实现
- 在ACM中Java关于大数的一些相关操作
- SAP 更改屏幕字段属性SHD0的使用方法
- 【学习笔记】【第一章】【Verilog HDL数字集成电路设计方法概述】
- KMP模板
- JavaScript 和文档对象模型(DOM)
- CENTOS下安装emacs 24.2
- Android学习笔记一:Application Fundamentals
- 嵌入式操作系统内核原理和开发(实时调度)