Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.0k views
in Technique[技术] by (71.8m points)

c++ - How I can remove every line that starts with "//" on an std::string?

I have the following template std::string

std::string myString = R"svg(
  <svg height={size} width={size}>
    <rect {...rectProps} x={x0h} y={y0h} />
    // <rect {...rectProps} x={x1h} y={y0h} />
    <rect {...rectProps} x={x0h} y={y1h} />
    // <rect {...rectProps} x={x1h} y={y1h} />
  </svg>
)svg";

And I will like to remove every line that starts with //

So the result I want will be like this

<svg height={size} width={size}>
  <rect {...rectProps} x={x0h} y={y0h} />
  <rect {...rectProps} x={x0h} y={y1h} />
</svg>

Edit: So my idea now is to iterate each line, trim it, and then detect if it starts with "//"

So far I have this in pseudo

std::istringstream stream(myString);
std::string line;
std::string myFinalString;
while (std::getline(stream, line)) {
  // TODO: trim line first
  bool isComment = false; // Find here if the line starts with //
  if (!isComment) {
    myFinalString += line + "
";
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

is not working as I expect

It definitely doesn't work the way it except you to. The overload of erase you use looks like

string& erase( size_type index = 0, size_type count = npos);

Description of the overload from cppreference:

Removes min(count, size() - index) characters starting at index.

So what you really do by svg.erase(0, svg.find("//") + 1) is you erase all the characters from index [0] up to [index of the last '/' you found]

Instead you should do the following:

  1. Search for "//" in your string, name this position A.
  2. Search for ' ' in your string, name this position B.
  3. Erase interval [A; B] from the string or [A; svg.length()] if you didn't find B
  4. Repeat until there is no more position A

P.s. I'd recommend to search from the end rather than from beginning because it would be easier to erase a piece form string if it is closer to the end than to the beginning

P.p.s. Also be sure to use iterators if you want to remove exactly intervals because the only overload of erase that removes intervals is

iterator erase( const_iterator first, const_iterator last );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...