字符串操作程序编译无警告但运行报错:Debug Assertion Failed! string subscript out of range
Hey there! That Debug Assertion Failed: string subscript out of range error is happening because your code is trying to access characters beyond the end of the text string in the bleep function. Let's break this down and fix it.
The Root Cause
Look at the outer loop in your bleep function:
for (int i = 0; i < text.size(); ++i)
You're looping i all the way to the last character of text. Then, inside this loop, you loop through each character of word with j, and access text[i + j]. When i is close to the end of text, i + j will exceed the length of text (since strings are 0-indexed). For example, if text has 21 characters (indices 0-20) and word has 8 characters, when i = 14, i + j can go up to 14 + 7 = 21, which is beyond the last valid index of text.
Fixed Code
Here's the corrected bleep function (plus a small efficiency improvement):
#include <string> #include <iostream> void bleep(std::string word, std::string &text) { using namespace std; // Only loop until i can fit the entire word in text for (int i = 0; i <= text.size() - word.size(); ++i) { cout << "i = " << i << endl; int matchCount = 0; for (int j = 0; j < word.size(); ++j) { cout << "j = " << j << endl; if (text[i + j] == word[j]) { ++matchCount; cout << "matchCount = " << matchCount << endl; } else { // No need to check further if current character doesn't match break; } } if (matchCount == word.size()) { for (int k = i; k < (i + word.size()); ++k) { cout << "k = " << k << endl; text[k] = '*'; } } } }
Why This Works
By changing the outer loop condition to i <= text.size() - word.size(), we ensure that i + j never exceeds text.size() - 1 (the last valid index of text). This eliminates the out-of-bounds access that was triggering the assertion.
The added break in the inner loop is optional but helpful—it stops checking characters as soon as one doesn't match, saving unnecessary work.
内容的提问来源于stack exchange,提问作者yurachika2020

