Search code examples
c++builderansistring

Checking for a character at end of AnsiString (and if finding), deleting it


I would like to check an AnsiString for a specific last character (in this case "f") and if finding it, then amending the AnsiString to remove it

Its likely to be obvious, but so far my searches have not worked.

A typical string it would be reading from disk could be:

"crit "Main Deck Aft" 37.80f 2.12 11.92"

You will see the one number has an "f" as a suffix, but this is not always the case. In such cases I want to remove it.

I also want to check the first character to be "-" as in negative, but first need to remove the suffix "f" before converting it to a float.

The last method I tried is, which compiles but does not trigger the if is

      char buffer[256];
      char *Buf, *Buf6, *Buf7, *Buf8, *Buf9, *Buf10;

      fgets(buffer,200,disk);
      if (strncmp(buffer,"crit \"",6) == 0)
      {
      CritCounter += 1;
      Buf = strtok(buffer,"\"");
      Buf6 = strtok(NULL,"\"");
      Buf7 = strtok(NULL," ,\t");
      Buf8 = strtok(NULL," ,\t");
      Buf9 = strtok(NULL," ,\t");
      Buf10 = strtok(NULL,"\n");
      AnsiString LongPos(Buf7);
      if (AnsiLastChar(LongPos) == "f")
      {
          LongPos.SetLength( LongPos.Length()-1 );
      }

Thanks in advance

Post Edited

This worked. Merely first assigning the last character to a new AnsiString and then using that AnsiString in the if worked

I can't see any difference it should have made

      AnsiString LongPos(Buf7);
      AnsiString LastChar = AnsiLastChar(LongPos);
      if (LastChar == "f")
      {
          LongPos.SetLength( LongPos.Length()-1 );
      }

versus this where if () == "f" did not trigger

      AnsiString LongPos(Buf7);
      if (AnsiLastChar(LongPos) == "f")
      {
          LongPos.SetLength( LongPos.Length()-1 );
      }

Solution

  • AnsiLastChar() (both the standalone function, and the AnsiString class method) returns a char* pointer to the last character. You DO NOT need to assign that pointer to another AnsiString in order to compare it, simply dereference the pointer instead, eg:

    char *LastChar = LongPos.AnsiLastChar();
    if (*LastChar == 'f')
        ...
    

    You cannot directly compare that pointer to another character pointer to check if they have the same character value. That is why if (AnsiLastChar(LongPos) == "f") is always false. A string literal like "f" is a const char[] array that decays into a const char* pointer. Comparing two pointers to each other simply compares their memory addresses, not the content of the data they are pointing at. The memory address that AnsiLastChar() returns will never equal the memory address of a string literal.