Substring find, replace, erase or regex?

Hello everyone,

i've read around many solutions to find and replace substring in a string.
I'm a little confused.

I need to parse a string as follow: /MySoftware/Development/Games

The final string should be as follow: MySoftware:Development/Games
I used some code found in this very site, but i had some problems.

As example:

1
2
3
4
5
6
7
8
9
10
11
12
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;

int main()
  {
  string s = "The quick brown fox jumps over the lazy dog.";
  replace( s.begin(), s.end(), ' ', '~' );
  cout << s << endl;
  return 0;
  }


this replace all the occurences in the string.
It is possible to find and replace the first occurence of a char?
In my case: /MySoftware/Development/Games i need to "cut" the first "/" and i have to replace the second "/" with ":"

Is regex a better soultution for this?

Thank you very much
I would do it like this;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <string>

using namespace std;

int main()
{
  string input = "/MySoftware/Development/Games";
 
  string output = input.substr(1); // remove leading '/'

  for (char& ch: output)
  {
    if (ch == '/') // first '/'
    {
      ch = ':'; // replace it
      break; // finish work
    }
  }
  cout << output << "\n\n";

  system("pause");
  return 0;
}
Another approach:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iomanip>
#include <iostream>
#include <string>

std::string myformat(const std::string& s) {
    if (s.empty()) return std::string{};

    std::size_t pos = s[0] == '/';
    std::size_t pos2 = s.find('/', pos);
    if (pos2 == std::string::npos) return s;

    return s.substr(pos, pos2-pos) + ':' + s.substr(pos2+1);
}

int main() {
    const std::string original = "/MySoftware/Development/Games";

    std::cout << std::quoted(original) << " becomes " ;
    std::cout << std::quoted(myformat(original)) << '\n' ;
}
With regex:
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <string>
#include <regex>

int main()
{
    std::string target = "/MySoftware/Development/Games";
    std::regex reg1("([/])");
    target = std::regex_replace(target, reg1, "", std::regex_constants::format_first_only);
    target = std::regex_replace(target, reg1, ":", std::regex_constants::format_first_only);
    std::cout << target << '\n';
}
closed account (L1vUM4Gy)
Another approach :

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>
#include <algorithm>

using namespace std;

string parse(string s)
{
	if(!s.empty())
	{
		if(s[0] == '/') s.erase(s.begin());

		string::iterator it;
		if((it = std::find(s.begin(), s.end(), '/')) != s.end()) *it = ':';
	}
	return s;
}

int main()
{
	const string original = "/MySoftware/Development/Games";

	string s = parse(original);

	cout << s << endl;

	return 0;
}
Topic archived. No new replies allowed.