STR CollapseWhitespaceT(const STR& text, bool trim_sequences_with_line_breaks) { STR result; result.resize(text.size()); // 设置标志位为true假设已经在连续空白中, 这样可以移除开头的全部空白. bool in_whitespace = true; bool already_trimmed = true; int chars_written = 0; for(typename STR::const_iterator i=text.begin(); i!=text.end(); ++i) { if(IsWhitespace(*i)) { if(!in_whitespace) { // 减少连续空白至一个空白. in_whitespace = true; result[chars_written++] = L' '; } if(trim_sequences_with_line_breaks && !already_trimmed && ((*i=='\n') || (*i=='\r'))) { // 包含回车换行的空白序列全部移除. already_trimmed = true; --chars_written; } } else { // 非空白字符直接拷贝. in_whitespace = false; already_trimmed = false; result[chars_written++] = *i; } } if(in_whitespace && !already_trimmed) { // 忽略末尾的全部空白. --chars_written; } result.resize(chars_written); return result; }
STR CollapseWhitespaceT(const STR& text, bool trim_sequences_with_line_breaks) { STR result; result.resize(text.size()); // Set flags to pretend we're already in a trimmed whitespace sequence, so we // will trim any leading whitespace. bool in_whitespace = true; bool already_trimmed = true; int chars_written = 0; for (typename STR::const_iterator i(text.begin()); i != text.end(); ++i) { if (IsWhitespace(*i)) { if (!in_whitespace) { // Reduce all whitespace sequences to a single space. in_whitespace = true; result[chars_written++] = L' '; } if (trim_sequences_with_line_breaks && !already_trimmed && ((*i == '\n') || (*i == '\r'))) { // Whitespace sequences containing CR or LF are eliminated entirely. already_trimmed = true; --chars_written; } } else { // Non-whitespace chracters are copied straight across. in_whitespace = false; already_trimmed = false; result[chars_written++] = *i; } } if (in_whitespace && !already_trimmed) { // Any trailing whitespace is eliminated. --chars_written; } result.resize(chars_written); return result; }