C++编程中遇到的问题总结

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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值