C++字符串空格替换题

在网络编程中,需要将URL参数中含有的特殊字符通过在‘%‘后加上ASCII码的两位十六进制的方法,转换成服务器端能够识别的字符,如空格的ASCII码为32即16进制的0x20,则需要替换为"%20"。

题目:请实现一个函数,把传入char*字符串中的每个空格替换成"%20",例如输入"We are happy.",则输出"We%20are%20happy."

时间复杂度为O(n)的解法思路:

首先遍历字符串,得到字符串长度originalLength并统计空格数numberOfBlank,可计算出替换后的字符串长度newLength = originalLength+2*numberOfBlank;

从字符串的尾部开始复制并向前移动,用两个下标IndexOfOriginal和IndexOfNew分别标记目前所指的原字符位置和替换后的字符位置;

当IndexOfOriginal指向空格时,IndexOfNew下标所指的字符及其往前1、2个位置分别替换为‘0‘、‘2‘、‘%‘,替换完成后IndexOfOriginal向前移动一格,IndexOfNew相应向前移动3格,否则都往前移动一格;

最后在字符串尾部即下标为newLength-1的位置添加‘\0‘。

代码:

void ReplaceBlank(char str[], int maxLength) {
    if(str == NULL || maxLength <=0)
        return;

    //calculate the new length after replacing and number of Blanks
    int originalLength = 0;
    int numberOfBlank = 0;
    int index = 0;
    for(index = 0; str[index] != ‘\0‘; index++) {
        if(str[index] == ‘ ‘)
            ++numberOfBlank;
    }
    originalLength = index+1;

    //if the number of blank is 0, nothing changes
    if(numberOfBlank==0)
        return;

    //if the new length exceeds the max length
    int newLength = originalLength+2*numberOfBlank;
    if (newLength > maxLength) {
        cout << "new Length exceeds the max Length!" << endl;
        return;
    }
    //start at the character before ‘\0‘
    int indexOfOriginal = originalLength-2;
    int indexOfNew = newLength-2;
    while (indexOfOriginal>=0 && indexOfNew > indexOfOriginal) {
        if (str[indexOfOriginal] == ‘ ‘) {
            str[indexOfNew--] = ‘0‘;
            str[indexOfNew--] = ‘2‘;
            str[indexOfNew--] = ‘%‘;
        } else {
            str[indexOfNew--] = str[indexOfOriginal];
        }
        --indexOfOriginal;
    }
    //add a ‘\0‘ at last
    str[newLength-1] = ‘\0‘;
}

完整代码:

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

void ReplaceBlank(char str[], int maxLength) {
    if(str == NULL || maxLength <=0)
        return;

    //calculate the new length after replacing and number of Blanks
    int originalLength = 0;
    int numberOfBlank = 0;
    int index = 0;
    for(index = 0; str[index] != ‘\0‘; index++) {
        if(str[index] == ‘ ‘)
            ++numberOfBlank;
    }
    originalLength = index+1;

    //if the number of blank is 0, nothing changes
    if(numberOfBlank==0)
        return;

    //if the new length exceeds the max length
    int newLength = originalLength+2*numberOfBlank;
    if (newLength > maxLength) {
        cout << "new Length exceeds the max Length!" << endl;
        return;
    }
    //start at the character before ‘\0‘
    int indexOfOriginal = originalLength-2;
    int indexOfNew = newLength-2;
    while (indexOfOriginal>=0 && indexOfNew > indexOfOriginal) {
        if (str[indexOfOriginal] == ‘ ‘) {
            str[indexOfNew--] = ‘0‘;
            str[indexOfNew--] = ‘2‘;
            str[indexOfNew--] = ‘%‘;
        } else {
            str[indexOfNew--] = str[indexOfOriginal];
        }
        --indexOfOriginal;
    }
    //add a ‘\0‘ at last
    str[newLength-1] = ‘\0‘;
}

void test(char str[], int maxLength) {
    cout << "-----------test-------------" << endl;
    printf("Original: %s\n", str);
    ReplaceBlank(str, maxLength);
    printf("Replaced: %s\n", str);
    cout << "-----------end---------------" << endl;

}
int main() {
    /*
    char str[50] = "hello world and s";
    ReplaceBlank(str, 50);
    printf("%s\n", str);
     */
    char str1[50]="hello world and s";
    char str2[50]="";
    char str3[20]="hello world! fdsjkd";
    char str4[50]="    helloweroddfsd";
    char str5[50]="       ";
    test(str1, 50);
    test(str2, 50);
    test (NULL, 50);
    test(str3, 20);
    test(str4, 50);
    test(str5, 50);
    return 0;
}

参考资料:《剑指Offer名企面试官精讲典型编程题》

时间: 2024-08-30 02:46:11

C++字符串空格替换题的相关文章

字符串空格替换、合法括号序列判断、求最长无重复子串问题

一:字符串空格替换 将字符串中的空格全部替换为"%20".假定该字符串后面有足够的空间存放新增的字符. 如:Mr John Smith->Mr%20John 陷阱:Java玩家可能第一时间想到用split(" ")分割原字符串,然后重新拼接的时候在词间添加"%20".这种思路的不完善之处在于:如果原字符串以空格结尾.或者单词之间不止一个空格,则会导致拼接出来的字符串不符合要求. 解法:该题说明原字符串后面有足够空间(Java玩家可忽略,因为

字符串 空格替换

题目描述 请编写一个方法,将字符串中的空格全部替换为“%20”.假定该字符串有足够的空间存放新增的字符,并且知道字符串的真实长度(小于等于1000),同时保证字符串由大小写的英文字母组成. 给定一个string iniString 为原始的串,以及串的长度 int len, 返回替换后的string. 测试样例: “Mr John Smith” 13 返回:“Mr%20John%20Smith”   “Hello World”,12 返回:“Hello%20%20World”   C++风格解法

1.4字符串 空格替换

1 class Replacement { 2 public: 3 string replaceSpace(string iniString, int length) { 4 // write code here 5 for(int m=0;m<iniString.size();) 6 { 7 int i=iniString.find(" ",m); 8 if(i==-1) 9 return iniString; 10 iniString.replace(i,1,"%2

《剑指Offer》替换空格(将字符串中的空格替换为%20)

题目: 请实现一个函数,将一个字符串中的空格替换成"%20".例如,当字符串为 We Are Happy.则经过替换之后的字符串为 We%20Are%20Happy. 思路: 这种替换问题要考虑是否会覆盖原字符串,若是在源字符串上直接替换. 看到这个问题我觉得很多人都会想到直接从头开始替换,即遇到空格就将其替换为%20,每次都要将空格后的字符后移两个字节.这种解法的时间复杂度为O(n^2)!!! 另外一种较好的解法是从后往前替换,具体做法是从头遍历计算所有空格数,计算出总的长度. 该解

替换空格:请实现一个函数,把字符串中的每个空格替换成“%20”

替换空格:请实现一个函数,把字符串中的每个空格替换成“%20”例如输入“we are best ”,则输出we%20are%20 best 此题的实际意义是在网络编程中,如果URL中含有特殊的字符如空格.‘#’等可能导致服务器无法获取正常的参数,我们需要将特殊字符转换成服务器可以识别的字符.准换的规则是“%”加上ASCLL的两位十六制表示,如空格的ASCLL值是32则十六进制为0x20 void replaceBlank(char *src,int length) { int oriLength

写一个函数,将字符串中空格替换为%20。

写一个函数,将字符串中空格替换为%20.样例:"abc defgx yz"替换为"abc%20defgx%20yz".这道题是一道简单的字符和字符串替换题,字符的替换直接用指针即可,每次都需要把空格后的字符串保存到一个数组中,然后把空格替换为%20后再将刚刚拷贝的字符串拷贝到%20的后面,代码如下: Fun(char str){char p = str;char arr[20];while (p != '\0'){if (p == ' '){strcpy(arr,

C语言之字符串数组空格替换

问题描述: 字符串替换空格:请实现一个函数,把字符串中的每个空格替换成"%20".例如输入"we are happy.",则输出"we%20are%20happy.". 代码实现: #include <stdio.h> int replace(char *p) { #if 0  while(*p!='\0')  {   if(*p==' ')   {    printf("%%20");   }   else   

将字符串中的空格替换为%20

------------------------------------------------------------------------------------------------------ 例如:有字符串we are family,实现后的字符串为we%20are%20family. 如果从前向后,遇空格替换空格,那么family必将向后移动两次:那么我们可以从后向前实现, 先预留足够的空间,先移动family,再移动are,遇空格填充即可. ------------------

实现函数,用字符串&quot;%20&quot;替换空格

题目及要求: 请实现一个函数,把字符串中的每个空格替换成"%20".例如输入"we are happy.",则输出"we%20are%20happy.". 思考过程:首先将定义一个指针,用于保存"%20",然后定义一个数组,用于接收从键盘上输入的字符串,边输入边判断,如果是空格,则替换,直至接收完毕. 程序: /* *实现一个函数,把字符串中的每个空格替换成"%20". *例如输入"we are