举个栗子:
We are happy-->输出"We%20are%20happy"ios
#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; }
注意:cin.getline(str,100);数组
- 第一个参数是字符指针
- 第二个参数是输入数组最大长度(’\0’会占据最后一位)
3.第三个参数是结束字符(不写默认回车),结束符不会被输入到数组中app
数组名的值是个指针常量,也就是数组第一个元素的地址。a[300]是一个数组,a是一个指向a[0]
的指针,a+5 是一个指向a[4]的指针ide
cin.getline()坑点spa
1.输入超过本身给getline()第二个参数设置的长度,整个程序的输入就终止了
2.cin.getline()读到第二个参数的长度或第三个参数符或者回车时结束输入,丢弃结束符。
好比cin.getlin(a,5,’-’);遇到‘-’结束输入,‘-’和‘\0’会被算进第二个参数5的个数里面,但‘-’最终会被丢出字符串,(就像‘-’凭空消失了同样,a中不会有,下一次的cin>>也不会读入他,就像cin.getline(a,5);遇到回车默认结束时,回车被丢出字符串同样);指针