c++ - 删除字符直到下一个 '\n'

标签 c++ c++98

我正在尝试从所有评论中清除我的字符串。 代码中的注释用“;”表示在句子前面。 有时程序的结尾用“;;”表示

假设我们有

push 34 ; example  
push 45  
add

为了检测出现的“;”我这样做:

std::size_t findComment = _string.find(";");

我希望能够做到这一点:

_string = _string.erase(findComment, '\n'); 

删除位置和第一个 '\n' 之间的所有内容。

提前致谢:)

更新:

我选择了 Konrad 的版本。它运作良好。但是如果用户在标准输出上写这个:

push int32(50)
push int32(50)
add
dump
;;

它应该执行函数并显示 100(转储显示堆栈)。但是因为它以“;;”结尾函数 trim_comments 删除函数转储。所以它没有被执行..

最佳答案

find has an overload它允许您指定开始搜索位置:

typedef std::string::size_type size_type;

size_type const comment_start = _string.find(";;");
size_type const newline = _string.find("\n", comment_start + 2);
if (newline == std::string::npos)
    _string.erase(comment_start);
else
    _string.erase(comment_start, newline - comment_start);

此外,请注意上面代码中 typedef 的使用,您的代码对 find 返回的位置使用了错误的类型。

但是,这段代码只删除了一条评论。通过从字符串中迭代eraseing 来删除多个注释是非常低效的。相反,您要做的是从非注释片段构建一个全新的字符串。要在 C++ 中高效地构建字符串,您可以使用 std::[o]stringstream class而不是裸露的 std::string

这是一个应该运行良好的示例实现:

std::string trim_comments(std::string const& code) {
    typedef std::string::size_type size_t;

    std::string const comment_start = ";;";
    std::ostringstream result;

    // Iteratively search for the start of the next comment and copy code before
    // that into the result.
    // We start by setting the previous comment end (the newline position) to
    // the start of the code.
    size_t newline_pos = 0;

    while (newline_pos != std::string::npos) {
        size_t const comment_pos = code.find(comment_start, newline_pos);

        if (comment_pos == std::string::npos) {
            // No more comments; copy the rest of the code from here until the
            // end into the result and quit.
            result << code.substr(newline_pos);
            break;
        }

        result << code.substr(newline_pos, comment_pos - newline_pos);
        // Find end of comment, assuming UNIX line endings.
        newline_pos = code.find('\n', comment_pos + comment_start.length());
    }

    return result.str();
}

您会注意到它比之前的短代码要复杂得多。这是我们为正确性付出的代价。更简单的解决方案需要更高级的文本处理功能,例如正则表达式(C++11 原生支持,并且可以通过库添加到 C++98)。

关于c++ - 删除字符直到下一个 '\n',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28646115/

相关文章:

c++ - 自动推导返回和参数类型的仿函数

C++ 模板类语法

c++ - 为有序链表 C++ 编写插入算法

java - 在单独的 Android 线程上调用时,emit 不起作用

c++ - 旧 C++ 编译器中的防护

c++ - 基本的shared_count变体

c++ - 给出编译错误的 const 对象的 vector

c++ - 搜索算法中的时钟函数通常返回 0

c++ - 使用 for 循环的 C 字符串赋值

c++ - ListView 控件无列标题