字符串替换问题

本文详细介绍了三种常见的字符串操作方法:字符替换、空格转义及连续空格删除,提供了具体实现代码,包括如何将特定字符移至字符串前端、将空格转换为%20以及删除连续空格。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*
字符串替换:
1.一个换一个
函数将字符串中的字符’‘移到字符串的前部分,前面的非’
字符后移,但不能改变非’‘字符的先后顺序,函数返回串中非’'字符的数量。(要求尽可能的占用少的时间和辅助空间)。
例如:原始串为autoch**ips,处理后为******autochips,函数返回9.
*/
在这里插入图片描述

#include<stdio.h>
#include<vector>
#include<string.h>
#include<string>
#include<iostream>
using namespace std;

int CheckString(char *str)
{
	int i = 0;
	int count = 0;
	int j;

	while(str[i] != '\0')
	{
		if(str[i] != '*')
			count++;
		i++;
	}

	while( i >= 0)
	{
		if(str[i] == '*')
		{
			j = i;
			while(j > 0 && str[j] == '*')
			{
				j--;
			}
			swap(str[j],str[i]);
		}
		i--;
	}
	cout << count << endl;
	return count;
}

int main()
{
	char str[100] = "abc**de**de**a*asd";
	int len = sizeof(str)/sizeof(str[0]);
	CheckString(str);
	cout << str << endl;
	return 0;
}

2.一个换多个(插入)
将空格替换成%20,见<剑指offer>例题4
时间复杂度为O(n),空间复杂度为O(1)

void replaceSpace(char *str,int length) 
{
	if(str != NULL && length <= 0)
		return ;
	  int i=0;
    int oldnumber=0;//记录以前的长度
    int replacenumber=0;//记录空格的数量
    while(str[i] != '\0')
    {
        oldnumber++;
        if(str[i]==' ')
        {
            replacenumber++;
        }
            i++; 
    }
    int newlength=oldnumber+replacenumber*2;//插入后的长度
    if(newlength>length)//如果计算后的长度大于总长度就无法插入
        return ;
    int pOldlength=oldnumber; //注意不要减一因为隐藏个‘\0’也要算里
    int pNewlength=newlength;
    while(pOldlength>=0&&pNewlength>pOldlength)//放字符
     {
         if(str[pOldlength]==' ') //碰到空格就替换
          {
                str[pNewlength--]='0';
                str[pNewlength--]='2';
                str[pNewlength--]='%';
                     
           }
          else //不是空格就把pOldlength指向的字符装入pNewlength指向的位置
          {
                str[pNewlength--]=str[pOldlength];
                   
          }
         pOldlength--; //不管是if还是elsr都要把pOldlength前移
	}
             
}
       
int main()
{
	char str[100] ="a b c d e";
	int len = sizeof(str)/sizeof(str[0]);
	replaceSpace(str,len);
	cout << str << endl;
	
	return 0;
}

3.多个换一个(删除)
将字符串中连续的空格删除,只保留一个空格"a b c d"->“a b c d”
时间复杂度为O(n),空间复杂度为O(1)

void replaceSpace(string &str,int length)
{
	int i = 0;
		
	if(length <= 1)
		return;
	while(str[i] != '\0')
	{
		int j = i + 1;
		if(str[i] == ' ' && str[j] == ' ')
		{
			while(str[j] != '\0' && str[j] == ' ')
			{
				j++;
			}
			swap(str[i + 1],str[j]);
		}
		++i;
	}
}
int main()
{
	string  str = "a b  c   d";
	replaceSpace(str,str.size());
	cout << str << endl;
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值