#include <iostream>
using namespace std;
int main()
{
char str1[] = "hello world";
char str2[] = "hello world";
char* str3 = "hello world";
char* str4 = "hello world";
if(str1 == str2) //分配两个空间,复制内容,比较他们的地址
cout << "str1 = str2" << endl;
else
cout << "str1 != str2" << endl;
if(str3 == str4) //无需分配内存,把它们指向"hello world"在内存中的地址
cout << "str3 = str4" << endl;
else
cout << "str3 != str4" << endl;
return 0;
}
题目:把字符串中的每个空格替换成"%20"。例如,输入"We are happy."则输出"We%20are%20happy."。
#include <iostream>
#include <string>
using namespace std;
void ReplaceBlank(string& str) //字符数组string的总容量,不是字符串长度或者字符个数
{
int actualLen = 0; //字符数组实际长度
int numBlank = 0; //空格个数
int i = 0;
while(str[i] != '\0') //遍历字符数组,统计长度
{
++ actualLen;
if(str[i] == ' ')
++ numBlank;
++i;
}
int newLen = actualLen + numBlank * 2;
str.resize(newLen); //调整字符数组的大小
int ptr_actual = actualLen - 1;
int ptr_newLen = newLen - 1;
while(ptr_actual >= 0 && ptr_newLen > ptr_actual)
{
if(str[ptr_actual] == ' ')
{
str[ptr_newLen --] = '0';
str[ptr_newLen --] = '2';
str[ptr_newLen --] = '%';
}
else
{
str[ptr_newLen --] = str[ptr_actual];
}
--ptr_actual;
}
}
int main()
{
string Mystr = "We are happy.";
ReplaceBlank(Mystr);
cout << Mystr << endl; // 输出替换空格后的字符串
return 0;
}
解题思路:遍历字符串,遇到空格替换成%20,在原字符串上操作的基础上,若从前往后复制和替换,由于string不存在负索引会覆盖原始字符串中未替换的部分,先遍历找出原始长度和空格数量,新长度等于原始长度加上空格数量*2,用两个指针指向新字符串的末尾str[新长度]、str[原始长度],从后往前遍历,没遇到空格就复制,遇到空格就替换,直到结束。时间复杂度为O(n)。