Franky N.
Franky N.

Reputation: 79

How to cut or delete some character in a string using c++

I have the following code:

#include <iostream>
using namespace std;
#include <string.h>

int main(){

 string track2;
 string Track2;
 string end_character("?");
 Track2={";80221000000100018A1301000000000000000?"};
 track2=Track2;

 cout<<"Track2={"<<Track2<<"}\n";

  if((track2.length()>=24 )  && (track2.find_first_not_of('0', 24) ==string::npos)){
     track2.erase (track2.begin()+24, track2.end());
  cout<<"\nTrack2={"<<track2<<"}\n";
  Track2=track2 + end_character;

  cout<<"\nTrack2={"<<Track2<<"}\n";
}
  else
     cout<<"Track2 has not more than 24 characters.\n";
}

I want to check first the length of the string track2, if this is bigger or equal to 24 character, then if the rest of character after the 24th character =0 and if the last character = ?. Then I will cut the string track2 at the begining of the 24th character until the end of track2. After that, I will insert the ? character at the end of the string track2 and printed this. Here is the expected output:

Track2={;80221000000100018A1301000000000000000?}

Track2={;80221000000100018A13010}

Track2={;80221000000100018A13010?}

But I have a problem and I cann't enter my if loop, when I put the character ? in my string. My program execute directely the else loop.

Could anyone help me to resolve this please? Thanks

Upvotes: 1

Views: 415

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409166

How about something like this:

if (Track2.length() > 24)
{
    auto question_mark_pos = Track2.find_first_not_of('0', 24);

    // If there is a character after the zeros AND
    // if that character is last AND
    // if that character is a question mark
    if (question_mark_pos != std::string::npos &&
        question_mark_pos == Track2.length() - 1 &&
        Track2[question_mark_pos] == '?')
    {
        // Get the first 24 characters of the string
        Track2 = Track2.substr(0, 24);

        // And append the special end character
        Track2 += end_character;
    }
}

Tested, and seems to work, here.

Upvotes: 2

Related Questions