Replacing each space string is "20%"

Replacing each space string is "20%"For chestnut:
We are Happy -> Output "We% 20are% 20happy"

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

//length是字符数组str的总容量
void ReplaceBlank(char *str, int length)
{
    if (str == nullptr&&length <= 0)
    {
        return;
    }
    int count = 0;
    int i = 0;
    int oldLength = 0;//str数组中原有长度
    while (str[i] != '\0')
    {
        if (str[i++] == ' ')
            ++count;
        ++oldLength;
    }
    int newLength = oldLength + count * 2;//加完所有%20之后的长度
    int index1 = newLength;
    int index2 = oldLength;
    if (newLength>length)
        return;
    while (index1 >= 0 && index2<index1)
    {
        if (str[index2] == ' ')
        {
            str[index1--] = '0';
            str[index1--] = '2';
            str[index1--] = '%';
            --index2;
        }
        else
        {
            str[index1--] = str[index2--];
        }
    }
}

int main()
{
    char str[] = "";
    cin.getline(str,100);//按行输入
    ReplaceBlank(str, 100);//100
    int i = 0;
    while (str[i] != '\0')
    {
        cout << str[i];
        i++;
    }
    return 0;
}

Note : cin.getline (str, 100);

  1. The first parameter is a character pointer
  2. The second parameter is the maximum length of the input array ( '\ 0' will occupy the last one)

3. The third parameter is the end character (do not write default carriage return), terminator will not be entered into the array

The value of the array name is a pointer constant, which is the address of the first element of the array. a [300] is an array, a is a pointer to a [0]
pointer, a + 5 is a pointer to a [4] pointer

cin.getline () pit

1 to their input exceeds getline () length of the second set of parameters, the input of the whole process is terminated
end 2.cin.getline () to read the length of the second or third parameter argument descriptor or carriage return input, discard terminator.
For example cin.getlin (a, 5, '- '); encounters '-' input end, '-' and '\ 0' will be counted into the number of the second parameter 5 inside, but the '-' will eventually It is thrown out strings (like '-' suddenly disappear, like, a there will not be, the next cin >> not read him like cin.getline (a, 5); encountered back At the end of the default car, carriage returns be thrown out like strings);

Guess you like

Origin blog.51cto.com/14233078/2452001