convert to an array of symbols
Dec 15, 2020 at 4:37pm UTC
Hi, i remember that someone helped me with this code here, thanks a lot for that. How can i write it as a charr array?
Q: "in a given string change all the entries of '$' to '*' until the first entry of '?' and delete all the '@' after '?' "
so it's like "$$?@@**$@" => "**?**$"
do i need to use <string.h>?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
//string test {"$@$?@$@"};
string test{ "$$?$@@" };
const auto at { find (test.begin(), test.end(), '?' ) };
if (at != test.end())
{
replace_if ( test.begin(), at, [](char ch) {return ch == '$' ; }, '*' );
test.erase ( remove_if(at, test.end(), [](char ch) {return ch == '@' ; }), test.end());
}
cout << test << '\n' ;
}
Dec 15, 2020 at 4:51pm UTC
You can basically keep the same code with just a couple of small changes as C++17:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
char test[] {"$$?@@**$@" };
if (const auto at {find(begin(test), end(test), '?' )}; at != end(test)) {
replace_if(begin(test), at, [](char ch) {return ch == '$' ; }, '*' );
test[remove_if(at, end(test), [](char ch) {return ch == '@' ; }) - test] = 0;
}
cout << test << '\n' ;
}
Dec 16, 2020 at 8:09am UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
#include <iostream>
int main()
{
char test[] = "$$?@@**$@" ;
int j = 0;
bool first = true ;
for ( int i = 0; test[i]; i++, j++ )
{
if ( first )
{
if ( test[i] == '$' ) test[i] = '*' ;
else if ( test[i] == '?' ) first = false ;
}
else
{
if ( test[i] == '@' ) j--;
else test[j] = test[i];
}
}
test[j] = '\0' ;
std::cout << test << '\n' ;
}
or with pointers:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
#include <iostream>
int main()
{
char test[] = "$$?@@**$@" ;
char *q = test;
bool first = true ;
for ( char *p = q; *p; p++, q++ )
{
char c = *p;
if ( first )
{
if ( c == '$' ) *p = '*' ;
else if ( c == '?' ) first = false ;
}
else
{
if ( c == '@' ) q--;
else *q = c;
}
}
*q = '\0' ;
std::cout << test << '\n' ;
}
Last edited on Dec 16, 2020 at 8:29am UTC
Topic archived. No new replies allowed.