1,字符串的末尾是’\0’,不是’/0’,否者下列程序运行时会字符串越界
int i = 0;
while (str[i] != '\0')
{
i++;
}
2题目是牛客网上剑指offer的第二题
题目描述
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
代码
class Solution {
public:
void replaceSpace(char *str,int length) {
}
};
可以正确运行的代码
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void main()
{
const int a = 100;
//string str = "we are happy";
char str[a] = "we are happy";
//string str1;
int i = 0;
int j = 0;
int length = 0;
int space_num = 0;
while (str[i] != '\0')
{
length++;
if (str[i] == ' ')
{
space_num++;
}
i++;
}
int len = length + space_num * 2;
while (length >= 0)
{
if (str[length] == ' ')
{
str[len--] = '0';
str[len--] = '2';
str[len--] = '%';
}
else
{
str[len--] = str[length];
//len--;
}
length--;
}
cout << str << endl;
system("pause");
}
错误的代码
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void main()
{
const int a = 100;
string str = "we are happy";
//char str[a] = "ABC CBA I LOVE YOU!";
//char str[a] = "we are happy";
//string str1;
int i = 0;
int j = 0;
int length = 0;
int space_num = 0;
while (str[i] != '\0')
{
length++;
if (str[i] == ' ')
{
space_num++;
}
i++;
}
int len = length + space_num * 2;
while (length >= 0)
{
if (str[length] == ' ')
{
str[len--] = '0';
str[len--] = '2';
str[len--] = '%';
}
else
{
str[len--] = str[length];
//len--;
}
length--;
}
cout << str << endl;
system("pause");
}
错误原因
因为操作的是字符串不是字符
class Solution {
public:
void replaceSpace(char *str,int length) {
}
};
C++中的string类型结尾没有’\0’,而char数组的结尾都是:’\0’,所以char类型数组的长度为看的长度+1,最后一个字符为’\0’
#include<iostream>
using namespace std;
int main()
{
char ch[]="7";
int a=sizeof(ch);
cout<<a<<"\t"<<ch[0]<<"A"<<ch[1]<<"A"<<endl;
string str="a";
cout<<str.size()<<endl;
cout<<str[0]<<endl;
return 0;
}
上述的结果
2 7AA
1
a