replace letter in a string

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

int main(void)
{
string test;
test="this is a test"
test.replace(' ','~')// replace the space with ~
cout << test;

return 0;
}


but it's not working can anyone help me?
http://www.cplusplus.com/reference/string/string/replace/

There is no overload for the function to run and replace every char a with char b. You need to write your own simple replace char function:
1
2
3
4
5
6
7
8
string replaceChar(string str, char ch1, char ch2) {
  for (int i = 0; i < str.length(); ++i) {
    if (str[i] == ch1)
      str[i] = ch2;
  }

  return str;
}


You could probably use the built-in functions and make a better function yourself, but here is the simplest version.

EDIT:
Here's a code for replacing characters already on the site found under
http://www.cplusplus.com/reference/string/string/find_first_of/ :

1
2
3
4
5
6
7
8
9
10
11
12
string replaceStrChar(string str, const string& replace, char ch) {

  // set our locator equal to the first appearance of any character in replace
  size_t i = str.find_first_of(replace);

  while (found != string::npos) { // While our position in the sting is in range.
    str[found] = ch; // Change the character at position.
    found = str.find_first_of(replace, found+1); // Relocate again.
  }

  return str; // return our new string.
}


Your call using this test string you have should be like:
test = replaceStrChar(test, " ", '*');
Last edited on
use the replace, begin and end function in c++ string.
You can view my post here: http://thecodewall.blogspot.com/2011/01/replace-all-specify-characters-in.html

http://codewall.blogspot.com
Last edited on
I like how thecodewall has an entire blog dedicated to how to do things the wrong way, and then has the audacity to require a login to post and tell him differently.

The replace member function works by refering to positions in the string not by searching for specific characters. Wolfgang's code would probably do what you are trying to accomplish.
Sigh.

You know, thecodewall did actually post the proper solution. He just left out a couple of required headers. (I don't know anything about the rest of his blog. Not that I care anyway.)

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 prints the text: "The~quick~brown~fox~jumps~over~the~lazy~dog."

Hope this helps.
I'm using codeblocks ide for all my c++ program in my blogs. Some compiler will require you to include algorithm and string but for code blocks it works with only iostream to include.

@Computergeek01 try to assist someone's work before leaving your comment. We are here to help someone's needed. Your name Computergeek is not proportionate to the knowledge you have. You did not know that there are more than 101 ways to solve programming problems. You commented about my blog but you did not post your own version of the solution. Actually you did not define replace as what it was and I know that you did not study it because you don't know that there was begin and end function and other parameter in replace that makes this problem easier to solve.

@Duoas Some c++ compiler did not require anymore some includes like we did before. Thanks for appreciate it.

http://codewall.blogspot.com
Last edited on
@thecodewall
Getting defensively arrogant, are we?

You want to trash computergeek01, who has been generally helpful here on the forums, with baseless ad homenim, and in the same post make uninformed assertations about the need to include required files. Just because compiler X works without including something does not make it correct code.

Always include the proper files for the functionality you use. If, behind the scenes, compiler X's standard library already includes some of them, there is no harm done. At least the code will work for those compilers that don't include them, since the code is standards-compliant.
*removed comment*
Last edited on
Okay, seriously. This is the point where I post a objection, despite my vow not to post today. Geez, I'm slipping.

@thecodewall:
Unfortunately, Duoas is right. First, you're rude when you're wrong. computergeek01 was right about replace(), only that he thought you meant a different replace() than the one you used (std::basic_string<char>::replace()). You also have a habit of ignoring standards, which is a problem in the programming world. I make it a rule to compile to the standard when compiling with g++ despite the leeway, and I think you should too to avoid this sort of treatment. That, and quit the arrogance, if you would be so kind. computergeek01, as Duoas pointed out, has generally been helpful around here, and while he made a mistake, Duoas corrected it. There was no need to post anything further, especially since you know very little about us.

@thesqlceilings (aka. a few certain persons who responded negatively to thecodewall's posts)
Despite the fact that thecodewall has made several grievous mistakes in both coding and behavior, that's no excuse to be treating him like I've seen you treating him: asking if you can shoot him and giving up on explaining standards to him. Remember: he's a human too, this is an impersonal connection, and you're supposed to be more mature than this.

-Albatross
Last edited on
I know I did not behave too well, I'm just getting a bit tired of people telling others what to do when they obviously don't know it themselves. Perhaps it's not this particular subject, but it has occurred countless of times with a countless number of people. I'm not saying that I am all-knowing myself, I'd just say that I don't take hasty conclusions or present half-done solutions - except for the exceptional case of a homework assignment, which we all call humor.

The shooting part was definitely not nice to say, but it wasn't completely without a reason either.
For everyone sorry and thank you I really appreciate it.

I post what I think may help.
I write the code... Its run well.
I posted here and somebody gave a lot of negative about it.
We are here to help.
If we has a new solution post it here.
Let the one chose for it.

And if my code is not in standard form does exactly wrong?
It's up to the one who use it, if he found error let him debug it. It may help him.

It's algorithm and idea that's count, it's not in the code. We know that there are more than 101 ways to solve a program. We know that we have different style of programming. You have a solution, I have my solution let the one who needs it choose.

http://codewall.blogspot.com
Last edited on
I don't think I gave "a lot" of negative feedback to your response, but I can understand your frustration with my post. Now, to give you some insight into my frustraiton, I don't hide the fact that I wear a dirty hat (although I swear my code has NEVER been released into the wild) and the patterns of your past posts to that point gave me the impression that you were a bot, a very well written one mind you but still an insult to what we are trying to do here. Honestly now that I've seen a genuinely human response from you my aggression has stopped completley.

As for the "bot patterns" that I'm refering to the dismissive "take my word as law" attitude with no follow up is seen, almost universally, as a sign of a strong character; but that fact is exploited by those who which to lend credibility to a non-sentient entity. Also you've been active on this site for about 4 to 6 months by my recollection and the relativley low number of posts associated with your account seemed odd to me, but if you really are a teacher I guess that would explain it somewhat. Really it's the vague clues to solutions, with no concreate answers you provided in your past posts and the constant spamming\plugging of your blog that raised my ire toward your tag. But as I stated before your outburst has erased that suspicion from me, and I won't give you anymore trouble.
Last edited on
For teacher which of these will you rely most for teaching students, your experiences or by the books?
I am a teacher. And that is a false dichotomy. The answer is, "both."

I criticized your code because you used a function from <algorithm> and a class from <string> without #including either. This is non-standard code, and it will fail to compile on at least one strictly conformant C++ compiler.

That some IDEs or compilers fix your mistake for you behind the scenes, whether that be on purpose or because one particular implementation of the STL was sloppy with includes, is not a valid rationalization for the "rightness" of explicitly omitting the proper includes. Doing that does not demonstrate any experience, but a lack of experience. (BTW, Code::Blocks is an IDE, and uses the GCC to compile your programs.)

After (kindly) remonstrations, having the chutzpah to make claims about the requirements for compiler implementations of the STL, to post incomplete code as a solution and claim it is for the "student's" good to have to deal with unexplained omissions like that, and to excuse yourself because "there are more than 101 ways to solve a [problem]," is pure nonsense. Teachers have a responsibility to proffer correct code and not saddle their students with incorrect practices. We have enough morons teaching students to use system() and other like cruft already. And, while there are often many ways to solve a problem, sometimes there are, actually, only one or two. In either case, once you choose a solution, it needs to be correct, else it isn't really a solution, is it?

I hate it when I do something stupid and get flack for it, but I have learned by experience it is best to simply accept the critisizm and not make the same mistake again. Perhaps you ought to do the same.

[edit] Fixed typo and added an adverb
Last edited on
And, while there are often many ways to solve a problem, sometimes there are, actually, only one or two. In either case, once you choose a solution, it needs to be correct, else it isn't really a solution, is it?


Not trying to be rude but based on your beliefs I guess you are not a Perl fan ? Perl provide multiple ways to solve a problem in terms of the language rich syntax I mean.

I have heard from my academic friends in teaching they hate to teach Perl cuz the whole language "rich" syntax obscure the teaching objectives. Imagine lab work when students submit programs that seem to like unless, until statement so much it attempt to do away with while, do-while for which we are more traditionally familiar with.

I am neutral on this issue. I use Perl extensively for it's regular expression and the speed is quite good too. Perl OOP is quite un-orthodox when you impose OO on a procedural language which I think only Larry Wall can come up with :P
Sohguanh, I think you're kind of missing his point; he said that although there are possibly infinite solutions, it's not wise to post a dependent solution when this can be avoided. If one compiler adds libraries automatically for you, then that's good, but still include them for compilers that don't. And since the standard doesn't say that it is possible that way, it's not necessary to be supported by all compilers, so they don't all add it by default.
Topic archived. No new replies allowed.