开发者

replace parts of a string with x's c++

I'm studying for a test tomorrow and doing a book problem in my C++ textbook.

we have barely done much with strings, but here is my problem.

//             name         ss#        username  password

string data = "Santa Claus 454-90-3424 sclaus passwordy"
string data2 = "Morgan Freeman 554-40-1124 mfree passwordx"

and I want to write a function that can work on both of those strings if need be that will replace the social security number with xxx-开发者_如何学Goxx-xxxx and the password with all x's for the number of characters in the password. how can I do this with simple string functions?


Look into tokenization. Separate the whole string by spaces, then replace the third and fifth sets with Xs.


Use the replace_if function in algorithm. (See the documentation and example code here). Your problem could be solved like this:

  #include <algorithm> // for replace_if
  #include <cctype> // for isdigit

  std::replace_if(data.begin(), data.end(), isdigit, 'x');
  // => Santa Claus xxx-xx-xxxx sclaus passwordy

  std::replace_if(data2.begin(), data2.end(), isdigit, 'x');
  // => Morgan Freeman xxx-xx-xxxx mfree passwordx
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜