looping through a string?

Hey everyone I'm not sure if this is a stupid question or not, but I thought of it now I want to know the answer. What is the most efficient way to loop through a string and parse it?

Here's how I would do it now:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
  #include <iostream>
#include <string>

using std::cout;
using std::string;
using std::endl;

void parseLine(string &line)
{
	constexpr char DELIMITER_ONE = '|';
	constexpr char DELIMITER_TWO = '[';
	for (int i = 0; i < line.length(); i++)
	{
		if (line[i] == DELIMITER_ONE || line[i] == DELIMITER_TWO)
		{
			line.erase(i, 1);
		}
	}
	cout << line << endl;
}
int main()
{
	std::string testString = "H|el[l|o|";
	parseLine(testString);

	system("pause");
	return 0;
}
Assuming your parsing a random/unknown string;

In terms of algorithmic speed/efficiency I think at best, o(n) is a "fast" as you can search through and parse a string.

In terms of c/c++ optimization tricks to speed things up I really have no idea.
Last edited on
More efficient (O(n) vs yours O(n2)):

1
2
3
4
//http://en.cppreference.com/w/cpp/algorithm/remove
//https://en.wikipedia.org/wiki/Erase%E2%80%93remove_idiom
line.erase( std::remove_if(line.begin(), line.end(), [](char c) { return c == '|' || c == '['; }),
            line.end() );
Topic archived. No new replies allowed.