删除字符串中各单词间多余空格

删除字符串中各单词间多余空格

编程实现删除字符串中各单词间多余空格,只保留一个空格。如果字首字符中有连续空格,应完全删除;如果非字母字符前后有空格应该将空格完全删除;如果末尾是一连续空格也应将其删除。

如:输入字符串“ I ’ m a student ! “,引号除外,输出结果为:“I’m a student!”,引号除外。

实现代码如下:

#include <cstdio>
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
string delspace(string st)//实现删除字符串中多余空格的函数
{
   if(st[0]==' ')//实现连续首字符空格的删除
    {
        int i;
        for(i=1;st[i]==' ';i++);
        st.replace(0,i,"");
    }
    for(int j=1,i=1;st[i]!='\0';)//实现字符间和末尾多余空格的删除
    {
        while(st[i]!=' '&&st[i]!='\0') i++;//寻找第一个空格位置
        if(st[i]=='\0') break;//寻找到字符串结尾就跳出循环
        for(j=1;st[i+j]==' ';j++);//统计空格数量
        if(st[i+j]=='\0'||!(st[i+j]>=65&&st[i+j]<=90||st[i+j]>=97&&st[i+j]<=122)||!(st[i-1]>=65&&st[i-1]<=90||st[i-1]>=97&&st[i-1]<=122)) st.replace(i,j,"");//非字母字符前后有空格完全删除,末尾连续空格将其删除
        else st.replace(i,j," ");//字符间保留一个空格
        while(st[i]==' ') i++;//寻找下一个非空格字符
    }
    return st;
 } 
 int main()
 {
    string st;
    getline(cin,st);
    cout<<delspace(st)<<endl;
    return 1;
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值