字符串下标超出范围(c++)
String subscript out of range (C++)
我遇到了这个问题,我不能放下,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_back
和operator+=
:
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
的大小
同样,如果对temp
和inStringP
使用相同的i
假设我们在字符e
处,它将跳过if block
和+1 i
。相应的temp
中的位置将保持不变。
同样,string.length()
返回不包括