c++ - 用不同字符替换单词的代码

标签 c++ string

此代码的目的是将具有 1 个字符的单词替换为“|”,将具有 2 个字符的单词替换为“||”,将具有 3 个字符的单词替换为“---”。 每次我运行它时都会出现错误:

string subscript out of range

知道是什么原因造成的吗?

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string text;
    int x, i, count=0;
    cout << "Enter the string of text you wish to modify" << endl << "(Make sure to inlude a period at the end of the text)" << endl;
    getline(cin, text);
    x = text.length();
    cout << x;
        if (text[x - 1] == '.')
        {
            for (i = 0; i <= x; i++)
            {
                count++;
                if (text[i] == ' ')
                {
                    if (count == 1)
                    {
                        text[i - 1] = '|';
                        count = 0;
                    }
                    else if (count == 2)
                    {
                        text[i - 2] = '|';
                        text[i - 1] = '|';
                        count = 0;
                    }
                    else if (count == 3)
                    {
                        text[i - 3] = '-';
                        text[i - 2] = '-';
                        text[i - 1] = '-';
                        count = 0;
                    }
                    else if (count > 4)
                    {
                        count = 0;
                    }
                }
                if (text[i] = '.')
                {
                    if (count == 1)
                    {
                        text[i - 1] = '|';
                    }
                    else if (count == 2)
                    {
                        text[i - 2] = '|';
                        text[i - 1] = '|';
                    }
                    else if (count == 3)
                    {
                        text[i - 3] = '-';
                        text[i - 2] = '-';
                        text[i - 1] = '-';
                    }
                }
            }
            cout << "Here is your modified sentence" << endl << text;
        }
    else
    {
        cout << "Your statement does not end in a period, goodbye" << endl;
    }
    return 0;
}

最佳答案

“下标超出范围”意味着您正在使用错误索引对数组进行索引。

尝试

 for(i=0;i<x;i++)

或者您可以使用带有 text.length() 的 switch 语句。

http://www.cprogramming.com/tutorial/lesson5.html

关于c++ - 用不同字符替换单词的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28890040/

相关文章:

c++ - 我应该将 printf 与 std::cin 混合使用吗?

string - Perl:返回字符串的最高匹配百分比

ios - 从 NSUserdefaults 转换/格式化 DateString

java - 如何使用字符串作为变量?

c++ - 使用 malloc/new 时无法编译 stm32l4r5xx

c++ - 在 C++ 中有效地管理数组二进制堆的句柄?

c++ - 组织解决方案,项目和SVN

c++ - 找到最接近的斐波那契数

javascript - 突出显示字符串中的文本

vb.net - 数组或列表中的项目是否保持其顺序?