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

C++编程中遇到的问题总结1 字符串的末尾是 0 不是 0 否者下列程序运行时会字符串越界 int i 0 while str i 0 i 2 题目是牛客网上剑指 offer 的第二题 题目描述

大家好,我是讯享网,很高兴认识大家。

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 
小讯
上一篇 2025-03-10 12:52
下一篇 2025-03-19 21:25

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/58118.html