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

阅读: 评论:0

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

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

1,字符串的末尾是’’,不是’/0’,否者下列程序运行时会字符串越界

	int i = 0;while (str[i] != ''){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] != ''){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] != ''){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类型结尾没有’’,而char数组的结尾都是:’’,所以char类型数组的长度为看的长度+1,最后一个字符为’’

#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       7AA1a

本文发布于:2024-01-31 22:30:37,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/170671143731842.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:
留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23