剑指offer:4-替换空格

本文介绍了一种算法,用于将字符串中的每个空格替换为%20。通过遍历字符串、计算空格数量和总长度,然后从后向前复制内容,并将空格替换为%20,最终得到替换后的字符串。

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


代码如下:

/*题目:实现一个函数,把字符串中的每个空格替换成“%20”。
例如输入“we are happy.”,则输出“we%20are%20happy.”。*/

/*
思路:
0.使用每个空格表示一个字符。
1.遍历字符串,求出空格数目。
2.计算当前字符串总长度,包括'\0'。
3.计算替换后需要的长度(增加空间:空格数*2)。
4.创建两个指针分别指向当前字符串末尾和替换后的字符串的末尾。
5.由后向前复制字符串内容,直到第一个指针遇到空格为止。
6.把空格替换成'%20',并第一个指针前移1格,第二个指针前移3格。
7.重复步骤5和6。
*/

#include <iostream>
using namespace std;

//length表示字符数组line[]的总容量,而非表示数组实际长度,可以自己给定.
int replaceBlank(char line[],int length)
{
	//line = new char[length];
	int flag = 0;
	//字符数组line为空字符数组.
	if(line == NULL || length <= 0)
	{
		flag = -1;
		return flag;
	}
	//odlLength表示替换前字符串实际长度.
	int odlLength = 0;
	int blankNumber = 0;
	int i = 0;
	//计算字符串总长度和其存在空格数.
	while (line[i] != '\0')
	{
		++odlLength;
		if(line[i] == ' ')
			++blankNumber;
		++i;
	}
	//末尾'\0'也占用一个空格.
	odlLength += 1;
	//若不存在空格,直接结束程序.
	if(blankNumber == 0)
	{
		flag = 1;
		return flag;
	}
	//newLength表示替换后的字符串实际长度.
	int newLength = odlLength + blankNumber * 2;
	//替换后的字符串长度大于原字符数组总容量.
	if (newLength > length)
	{
		flag = 2;
		return flag;
	}
	//定义数组下标.
	int p = odlLength - 1;
	int q = newLength - 1;//cout << "p: " << p << ", q: " << q;
	while (p >= 0 && q > p)
	{
		//不管是字符还是'\0'均替换.
		if(line[p] != ' ')
		{
			line[q] = line[p];////////////////////////////////////////////////////////////
			--q;
			--p;
		}
		//若为空格
		else
		{
			//第二个指针前移3格
			line[q--] = '0';
			line[q--] = '2';
			line[q--] = '%';
			//第一个指针前移1格
			--p;
		}
	}
	return flag;
}

// ====================测试代码====================
void test(char *testName,char *line,int length,int expected)
{
	if(testName != NULL)
		cout << testName << ": ";
	int k = replaceBlank(line,length);//每次调用函数replaceBlank都会发生计算.
	cout << k << "," << expected <<"/";
	if (k == expected)
		cout << "Passed!";
	else
		cout << "Faled!";
	cout << endl;
}

//字符数组为空字符数组.
void test1()
{
	int const length = 10;
	//char testLine[] = "";//注意:此时sizeof(testLine)=1.
	char *testLine = NULL;
	test("test1",testLine,10,-1);
}

//正常情况下替换.
void test2()
{
	int const length = 18;
	char testLine[length] = "we are happy!";
	test("test2",testLine,length,0);
}

//字符串中不存在空格的情况.
void test3()
{
	int const length = 18;
	char *testLine = "wearehappy!";
	test("test3",testLine,18,1);
}

//替换后的字符串长度大于原字符数组总容量.
void test4()
{
	int const length = 10;
	char *testLine = "we are happy!";
	test("test4",testLine,length,2);
}

//字符串中存在连续多个空格的情况.
void test5()
{
	int const length = 30;
	char testLine[length] = "we   are   happy!";
	test("test5",testLine,length,0);
	cout << "testLine: " << testLine << endl;
}

int main()
{
	test1();
	test2();
	test3();
	test4();
	test5();
	return 0;
}

运行结果如下:


原书代码如下:

// ReplaceBlank.cpp : Defines the entry point for the console application.
//

// 《剑指Offer——名企面试官精讲典型编程题》代码
// 著作权所有者:何海涛

#include <iostream>
#include <string>
using namespace std;

/*length 为字符数组string的总容量*/
void ReplaceBlank(char string[], int length)
{
    if(string == NULL && length <= 0)
        return;

    /*originalLength 为字符串string的实际长度*/
    int originalLength = 0;
    int numberOfBlank = 0;
    int i = 0;
    while(string[i] != '\0')
    {
        ++ originalLength;

        if(string[i] == ' ')
            ++ numberOfBlank;

        ++ i;
    }

    /*newLength 为把空格替换成'%20'之后的长度*/
    int newLength = originalLength + numberOfBlank * 2;
    if(newLength > length)
        return;

    int indexOfOriginal = originalLength;
    int indexOfNew = newLength;
    while(indexOfOriginal >= 0 && indexOfNew > indexOfOriginal)
    {
        if(string[indexOfOriginal] == ' ')
        {
            string[indexOfNew --] = '0';
            string[indexOfNew --] = '2';
            string[indexOfNew --] = '%';
        }
        else
        {
            string[indexOfNew --] = string[indexOfOriginal];
        }

        -- indexOfOriginal;
    }
}

void Test(char* testName, char string[], int length, char expected[])
{
    if(testName != NULL)
        printf("%s begins: ", testName);

    ReplaceBlank(string, length);

    if(expected == NULL && string == NULL)
        printf("passed.\n");
    else if(expected == NULL && string != NULL)
        printf("failed.\n");
    else if(strcmp(string, expected) == 0)
        printf("passed.\n");
    else
        printf("failed.\n");
}

// 空格在句子中间
void Test1()
{
    const int length = 100;

    char string[length] = "hello world";
    Test("Test1", string, length, "hello%20world");
}

// 空格在句子开头
void Test2()
{
    const int length = 100;

    char string[length] = " helloworld";
    Test("Test2", string, length, "%20helloworld");
}

// 空格在句子末尾
void Test3()
{
    const int length = 100;

    char string[length] = "helloworld ";
    Test("Test3", string, length, "helloworld%20");
}

// 连续有两个空格
void Test4()
{
    const int length = 100;

    char string[length] = "hello  world";
    Test("Test4", string, length, "hello%20%20world");
}

// 传入NULL
void Test5()
{
    Test("Test5", NULL, 0, NULL);
}

// 传入内容为空的字符串
void Test6()
{
    const int length = 100;

    char string[length] = "";
    Test("Test6", string, length, "");
}

//传入内容为一个空格的字符串
void Test7()
{
    const int length = 100;

    char string[length] = " ";
    Test("Test7", string, length, "%20");
}

// 传入的字符串没有空格
void Test8()
{
    const int length = 100;

    char string[length] = "helloworld";
    Test("Test8", string, length, "helloworld");
}

// 传入的字符串全是空格
void Test9()
{
    const int length = 100;

    char string[length] = "   ";
    Test("Test9", string, length, "%20%20%20");
}

int _tmain(int argc, _TCHAR* argv[])
{
    Test1();
    Test2();
    Test3();
    Test4();
    Test5();
    Test6();
    Test7();
    Test8();
    Test9();

    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值