字符串下标超出范围(c++)

String subscript out of range (C++)

本文关键字:c++ 范围 下标 字符串      更新时间:2023-10-16

我遇到了这个问题,我不能放下,visual c++ 2010一直告诉我:"表达式:字符串下标超出范围"。我认为我运行的循环比"stringp .length()"的长度长,所以我添加了&从for循环的条件测试中的整数中减去1或2,但这不会导致成功。谷歌今天也没有像往常一样的天才了.....

#include <iostream>
#include <cstdlib>
#include <string>
#include "stdAfx.h"
using namespace std;
string removeChar(string inStringP){
   string temp;
   for(int i=0;i<inStringP.length()-1;i++){
      if(inStringP[i]!='p'){
         temp[i]=inStringP[i];
      }
   }
   return temp;
}
int main(){
   string sample = "Peter picks a peck of pickled peppers";
   cout<<removeChar(sample)<<endl;
   system("PAUSE");
   return EXIT_SUCCESS;
}

你的应用程序崩溃是因为下面的语句没有为temp分配任何元素,访问temp[0]未定义的行为

string temp;

如果你想在removeChar函数中使用temp,更好的方法是将const引用传递给stringp

string removeChar(const string& inStringP){
}

通过这样做,您不需要在输入removeChar函数时复制到stringp。

更好的方法是遵循擦除-删除习惯用法:

试题:

string removeChar(string inStringP)
{
    return inStringP.erase(std::remove(sample.begin(), sample.end(), 'p'), sample.end());
}

使用前

resize temp

string temp;
temp.resize(inStringP.size());

当你一开始不知道实际尺寸时,你可以append, push_backoperator+=:

temp.append(1, inStringP[i]);
or
temp.push_back(inStringP[i]);
or
temp += inStringP[i];

你可以尝试使用string.erase()吗?

http://www.cplusplus.com/reference/string/string/erase/

迭代器版本允许删除字符…使用迭代器搜索字符串,然后使用erase函数删除字符串,该函数接受迭代器作为实参

编辑:看billz的回答…非常好!

当你使用std::string时,你也可以使用算术运算符。

你可以这样做,

   for(int i=0;i<=inStringP.length();i++)
   {
      if(inStringP[i]!='p')
      {
         temp += inStringP[i];
         cout<<temp<<endl;
      }
   }

我在g++ 4.6.3上尝试了你的代码,没有给出任何错误。然而,它给了

for循环结束时设置一个空白temp;

对于temp[i] = inString[i],编译器还没有temp的大小

同样,如果对tempinStringP使用相同的i假设我们在字符e处,它将跳过if block和+1 i。相应的temp中的位置将保持不变。

同样,string.length()返回不包括的字符串长度

我推荐;

string removeChar(string inStringP){
   string temp;
   int len = inStringP.length();
   for(int i = 0;i < len;i++){
      if(inStringP[i] != 'p'){
        temp.push_back(inStringP[i]);
      }
   }
   return temp;
}

因为你的逻辑给出了非编译时错误,但它是一个运行时错误。你的代码实际上是这样工作的:

string temp;
    temp[0] = 'P';
    temp[1] = 'e';
    temp[2] = 't';
    temp[3] = 'e';
    temp[4] = 'r';
    temp[5] = ' ';
    //s[6] = 'p';
    temp[7] = 'i';