How can I replace multiple characters with just one (C++)? - c++

We have a char. We need to replace all ab characters from our char with the letter c.
Example we have :
abracadabra
the output will be :
cracadcra
I tried to use replace() function from C++, but no success.
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
string test;
cin>>test;
for(int i=0;i<(strlen(test)-1);i++)
{
if((test[i]=='a')&&(test[i+1]=='b')){
test.replace( test[i], 'c' );
test.replace( test[i+1] , ' ' );
}
}
cout << test << endl;
return 0;
}enter code here

You can use C++11 regex:
#include <iostream>
#include <regex>
#include <string>
int main() {
std::string str = "abracadabra";
std::regex r("ab");
std::cout << std::regex_replace(str, r, "c") << "\n"; // cracadcra
}

Problem:
That is not the syntax of std::string::replace.
Solution:
As is mentioned here the syntax is std::string::replace(size_t pos, size_t len, const string& str). Do test.replace(i, 2, "c" ) instead of test.replace(test[i],'c').
Or use regular expressions as dtell pointed.
Adittional information:
using namespace std; is considered a bad practice (More info here).
You should use std::string::size instead of strlen when you're working with std::string.
To work with std::string you should use #include <string> instead of #include <cstring>.
Full code:
#include <iostream>
int main()
{
std::string test;
std::cin >> test;
for(unsigned int i = 0; i < test.size() - 1; i++)
{
if((test[i]=='a') && (test[i+1]=='b'))
{
test.replace(i, 2, "c" );
}
}
std::cout << test << std::endl;
return 0;
}

The simplest thing you can do by using the standard library is first to find ab and then replace it. The example code I wrote is finding string ab unless there is None in the string and replacing it with c.
#include <iostream>
#include <string>
int main()
{
std::string s = "abracadabra";
int pos = -1;
while ((pos = s.find("ab")) != -1)//finding the position of ab
s.replace(pos, sizeof("ab") - 1, "c");//replace ab with c
std::cout << s << std::endl;
return 0;
}
//OUTPUT
cracadcra

Related

Get last part of URL

How would I get the last part of a URL?
Say the variable url is https://somewhere.com/stuff/hello.
How would I get hello from this?
Using rfind and substr
Maybe with
#include <iostream>
#include <string>
int main() {
std::string url{"https://somewhere.com/stuff/hello"};
std::cout << url.substr(url.rfind('/')+1);
return 0;
}
But only, if you have a / in front of the last part
#include <iostream>
#include <string>
int main() {
const std::string url("https://somewhere.com/stuff/hello");
const std::size_t indexLastSeparator = url.find_last_of("/");
if (indexLastSeparator != std::string::npos)
{
const std::string lastPartUrl = url.substr(indexLastSeparator+1); // +1 to not keep /
std::cout << lastPartUrl << '\n'; // print "hello"
}
}
With find_last_of() and substr()
references :
https://en.cppreference.com/w/cpp/string/basic_string/find_last_of
https://en.cppreference.com/w/cpp/string/basic_string/substr

Alternative for a loop in C++

I want to reverse a string without the use of a loop. My code with the loop looks like:
#include <iostream>
#include <string>
using namespace std;
string reverseString(string str) {
string changedString;
int strLength = int(str.length() - 1);
for(int i {strLength}; i >= 0; i--) {
changedString.push_back(str.at(i));
}
return changedString;
}
int main() {
string str;
cout << "Enter a string to reverse it:\n" << flush;
cin >> str;
cout << reverseString(str) << flush;
}
Now I need to write a function without the loop. Only the methods of String should be used. Can you help me solving this problem?
It is very simple to write such a function
std::string reverse( const std::string &s )
{
return { s.rbegin(), s.rend() };
}
Here is a demonstrative program
#include <iostream>
#include <string>
std::string reverse( const std::string &s )
{
return { s.rbegin(), s.rend() };
}
int main()
{
std::string s( "Hello World" );
std::cout << s << '\n';
std::cout << reverse( s ) << '\n';
return 0;
}
Its output is
Hello World
dlroW olleH
Well, you can do that using recursion. Here are some links if you aren't aware what recursion is : link1 and link2.
Technically it won't be a loop.
string reverseString(string str, int index, string ans) {
if (index == -1) return ans;
ans += str[index];
return reverseString(str, index - 1, ans);
}
Parameters for this function will be str as it was by default, index = size(str) - 1 and ans ans = "";
reverseString(str, size(str) - 1, "") for example.
If you want your function to take exactly one argument, then you can write wrapper function and the one I wrote will have different name - reverseStringWrapper for example and in reverseString there will be only one line - return reverseStringWrapper(str, size(str) - 1, "");
string reverseStringWrapper(string str, int index, string ans) {
if (index == -1) return ans;
ans += str[index];
return reverseString(str, index - 1, ans);
}
string reverseString(string str) {
return reverseStringWrapper(str, size(str) - 1, "");
}
How was this?
In c, You can use strrev() function to reverse the string(char*)
In c++, you can either use std::reverse() or StringBuilder.reverse()
method to reverse a string.
.
This way you can reverse the char array(char*).
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
// Function to reverse a given character array using std::reverse
void reverse(char *str)
{
std::reverse(str, str + strlen(str));
}
// main function
int main()
{
/* using C string */
char s[] = "Hello World";
reverse(s);
cout << "Reverse of the given string is : " << s;
return 0;
}
This way you can reverse the string.
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
// Function to reverse a given character array using std::reverse
void reverse(char* str)
{
std::reverse(str, str + strlen(str));
}
// main function
int main()
{
/* using C string */
// char s[] = "Techie Delight";
string s = "hello world";
int n = s.length();
// declaring character array
char char_array[n + 1];
// copying the contents of the
// string to char array
strcpy(char_array, s.c_str());
reverse(char_array);
s = char_array;
cout << "Reverse of the given string is : " << s;
return 0;
}
Hope this might Helps:)

How to add a char into a string

So I am creating an hangman game and want to add a char into a string. I want to add a char of guess to the gatherguess string until the gatherguess matches hangman. Feel free to add some helpful tips to my code that will make me better. Also if it would be more then nice if you can also give me some sample code with dynamic memory allocation.
#include <stdio.h>
#include <string.h>
#include <iostream> // std::cout
#include <stdio.h>
#include <string.h>
#include <iostream> // std::cout
#include <algorithm> // std::for_each
#include <vector>
#include <set>
#include <string>
bool isitdone(std::string foo, std::string hang){
return foo == hang ? true : false ;
}
int main(){
std::string hangman;
char guess;
std::string gatherguess; //Get the letters guessed.
std::cin >> hangman; //Player enter the word to guess.
bool checkstatement; // Check to see if game is over.
for(int i =0; i < 10; ++i) {
std::cin >> guess; //Individual characters to guess
std::string doo;
int wordsin;
doo = hangman;
int y;
if(doo.rfind(guess) != std::string::npos) {
std::cout << "Right " << guess << " Is in the word" << std::endl;
std::cout << std::endl;
checkstatement = isitdone(gatherguess,doo);// I want to add guess char into gatherguess
//then check to see if gatherguess is equal to the word then the game will be complete
if(checkstatement == true) {
return 0;
}
} else {
std::cout << "Wrong" << std::endl;
}
}
return 0;
}
First of all, you should initialize gatherguess with enough placeholder characters:
auto hangman = std::string{};
std::cin >> hangman;
auto gatherguess = std::string{hangman.size(), '_'};
Now you can simply overwrite the '_' characters.
auto pos = hangman.find(guess)
if(pos != std::string::npos) {
// ...
do {
gatherguess[pos] = guess; // overwrite
pos = hangman.find(guess, pos); // find next ocurrence
} while(pos != std::string::npos)
// ...
}
I made some changes on your code. It contains some pieces of advice as comment.
//#include <stdio.h> // Do not include a library if you don not use it, because it makes the performance worse.
//#include <string> // Do not include a library if you don not use it, because it makes the performance worse.
#include <iostream> // std::cout
//#include <stdio.h> // It is pointless to include a library twice.
//#include <string.h>
//#include <iostream> // std::cout
//#include <algorithm> // std::for_each
//#include <vector> // Do not include a library if you don not use it, because it makes the performance worse.
//#include <set> // Do not include a library if you don not use it, because it makes the performance worse.
#include <string>
bool isitdone(const std::string& foo, const std::string& hang){ // Passing argument by const reference makes performance much better.
return foo == hang ? true : false ; // Indenting makes the code much more readable.
}
int main(){
const int N=10; // Store constant number in constant variable, because you can change its' value later easily.
std::string hangman;
char guess;
std::string gatherguess; //Get the letters guessed.
std::cin >> hangman; //Player enter the word to guess.
bool checkstatement; // Check to see if game is over.
for(int i =0; i < N; ++i)
{
std::cin >> guess; //Individual characters to guess
std::string doo;
int wordsin;
doo = hangman;
int y;
if(doo.rfind(guess) != std::string::npos)
{
std::cout << "Right " << guess << " Is in the word" << std::endl;
std::cout << std::endl;
checkstatement = isitdone(gatherguess,doo);// I want to add guess char into gatherguess
//then check to see if gatherguess is equal to the word then the game will be complete
if(checkstatement == true)
{
return 0;
}
} else
{
std::cout << "Wrong" << std::endl;
}
}
return 0;
}
I think there is a logical mistake in your program. What happens if a word contains more than 10 different characters? Do not count if the tipp is right.
You can add a char to a string this way:
#include <iostream>
#include <string>
int main(){
std::string str="123";
str+='4';
std::cout<<str<<std::endl;
return 0;
}

most efficient way to parse a string using c++ features

this might be a stupid question (I hope not) but it caught my mind and I'm trying to figure it out. What is the most efficient way to parse a string using c++ features?
I appreciate everyone's comments as I, am I'm sure everyone else is too, to become a better programmer!
Here is how I would do it right now with my current knowledge:
#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;
}
line.erase(
std::remove_if(line.begin(), line.end(),
[](char c) { return c == DELIMITER_ONE || c == DELIMITER_TWO; }
),
line.end()
);
See also: erase-remove idiom
One more way is to use the boost regex library. Check the below code:
#include <iostream>
#include <string>
#include <boost/regex.hpp>
int main(){
std::string testString = "H|el[l|o|";
boost::regex rx("\\||\\[");
std::string replace = "";
std::string out = boost::regex_replace(testString, rx, replace);
std::cout << out << std::endl;
}
C++14 now includes regular expressions standard:
#include <iostream>
#include <string>
#include <regex>
std::string parseLine(const std::string& line);
int main() {
std::string testString = "H|el[l|o|";
std::string result = parseLine(testString);
std::cout << result << std::endl;
system("pause");
return 0;
}
std::string parseLine(const std::string& line) {
std::string input_string;
std::string result;
std::smatch sm;
std::regex r("([a-zA-Z]+)");
for(input_string = line; std::regex_search(input_string, sm, r); input_string = sm.suffix()) {
result.append(sm[0].str());
}
return result;
}

getting a sub string of a std::wstring

How can I get a substring of a std::wstring which includes some non-ASCII characters?
The following code does not output anything:
(The text is an Arabic word contains 4 characters where each character has two bytes, plus the word "Hello")
#include <iostream>
#include <string>
using namespace std;
int main()
{
wstring s = L"سلام hello";
wcout << s.substr(0,3) << endl;
wcout << s.substr(4,5) << endl;
return 0;
}
This should work: live on Coliru
#include <iostream>
#include <string>
#include <boost/regex/pending/unicode_iterator.hpp>
using namespace std;
template <typename C>
std::string to_utf8(C const& in)
{
std::string result;
auto out = std::back_inserter(result);
auto utf8out = boost::utf8_output_iterator<decltype(out)>(out);
std::copy(begin(in), end(in), utf8out);
return result;
}
int main()
{
wstring s = L"سلام hello";
auto first = s.substr(0,3);
auto second = s.substr(4,5);
cout << to_utf8(first) << endl;
cout << to_utf8(second) << endl;
}
Prints
سلا
hell
Frankly though, I think your substring calls are making weird assumptions. Let me suggest a fix for that in a minute: