trimCharactersAtEnd() bug?

If I create a path string like:
String myPath ( “/Users/myname/Documents/myparentfolder/myfolder/” );

and I later call
String otherPath = myPath.trimCharactersAtEnd("/");

the result is exactly the same as the original. The “/” at the end is not removed!? Instead, I have to do something like this:

String otherPath = (myPath.endsWith("/")) ? myPath.upToLastOccurenceOf( “/”, false, false ) : myPath;

Is this a bug, or to be expected for some reason?

Please can you post the exact code that is causing the problem? I added the following tests and they passed, as I would expect.

expectEquals (String ("/path/to/folder/").trimCharactersAtEnd ("/"), String ("/path/to/folder"));
expectEquals (String ("/path/to/folder/").trimCharactersAtStart ("/"), String ("path/to/folder/"));

Unrelated I would strongly advice using the File methods for modifying paths and ascending/descending the file tree:
File::getSpecialLocation() or chooser.getFiles() as starting point and from there using getParentDirectory() and getChildFile(“foo”).

That is definitely portable regarding of slash and backslash etc.

2 Likes

Oh, I see my problem. The function returns a copy of the string. It doesn’t modify the string itself. (My code posted above was not what I actually used, which tried to use that function in place.)

The name made me think it was trimming the string itself, not creating a new string. Something like withCharactersTrimmedFromEnd() would have been more obvious. :slight_smile:
Thanks! Carry on!

1 Like