Truncating Strings--an Expert needs novice help!

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • RedSon
    Recognized Expert Expert
    • Jan 2007
    • 4980

    Truncating Strings--an Expert needs novice help!

    Here is the problem:

    I have a path to a file like \Windows\Start Menu\Accessorie s\Calculator.ln k and I am trying to truncate it down to just "Calculator ".

    Code:
    _tcscpy(pItem->label, recentItem->path);
    *wcsrchr (pItem->label, '.') = '\0';
    First I am copying the recentItem (which is just a struct that has a TCHAR array called path -- which is the path to the shortcut) path to the pItem (which is just a struct that my WinMain method uses to populate a popup menu, that contains a label and a path -- where label is like "Calculator "). Then I truncate the label to remove the .lnk, so I am left with \Windows\Start Menu\Accessorie s\Calculator. Now I want to get rid of everything up to the last back-whack. Any ideas? I'm using all Win32 stuff here.
  • Ganon11
    Recognized Expert Specialist
    • Oct 2006
    • 3651

    #2
    You have the path in a string/character array, correct?

    Then just search backwards through the array for the 'first' occurrence of the \ character - this will be the position of the last \ character in the string. Then get the substring from that position + 1 to the end of the string.

    Comment

    • RedSon
      Recognized Expert Expert
      • Jan 2007
      • 4980

      #3
      Originally posted by Ganon11
      You have the path in a string/character array, correct?

      Then just search backwards through the array for the 'first' occurrence of the \ character - this will be the position of the last \ character in the string. Then get the substring from that position + 1 to the end of the string.
      Right, but what is the methods for that?

      Comment

      • Ganon11
        Recognized Expert Specialist
        • Oct 2006
        • 3651

        #4
        Assuming your path is in a string called fpath,

        Code:
        int position;
        for (int i = fpath.length() - 1; i >= 0; i--) {
           if (fpath[i] == '\\') // Because \ is escape sequence generator, and \\ is required to print \
              position = i;
              break;
           }
        }
        
        // Position now holds the location of the last '\' in fpath.
        fpath = fpath.substr(position + 1);
        Since you don't want to include the \ in your new filepath, you add 1 to the position is in in to get the entire string after it.

        Comment

        Working...