Henry Olive 5 Posted November 24, 2023 Good Day, MyString could be 'Aaaa Bbbb <Axx Bxx>' or just '<Axx Bxx>' In any case i'd like delete just the part of <Axx Bxx> (Including < and >) What is the shortest way ? Thank You Share this post Link to post
Lars Fosdal 1786 Posted November 24, 2023 Result := MyString StartPos := Pos('<', Result); if StartPos > 0 then Delete(Result, StartPos, Pos('>', Result) - StartPos + 1); Something like this? Note that it doesn't handle a missing '>', nor does it trim. Share this post Link to post
Remy Lebeau 1375 Posted November 24, 2023 3 hours ago, Lars Fosdal said: Delete(Result, StartPos, Pos('>', Result) - StartPos + 1); Minor nitpick - you should pass in StartPos as a 3rd parameter to the 2nd Pos() call: Delete(Result, StartPos, Pos('>', Result, StartPos+1) - StartPos + 1) You might also want to Trim/Right() the Result after deleting the characters. 1 Share this post Link to post
David Heffernan 2345 Posted November 24, 2023 What do you mean by "shortest"? Share this post Link to post
Remy Lebeau 1375 Posted November 24, 2023 If the '<...>' is always at end of the string then you could just SetLength() the string to truncate it, eg: Result := MyString; StartPos := Pos('<', Result); if StartPos > 0 then begin SetLength(Result, StartPos - 1); Result := TrimRight(Result); end; Share this post Link to post
corneliusdavid 209 Posted November 27, 2023 If by "shortest" you're trying to keep it to one line, this will work (you have to use the Math and StrUtils units): Result := IfThen(Pos('<', MyStr) > 0, Trim(LeftStr(MyStr, Pos('<', MyStr) - 1)), MyStr); Share this post Link to post
Lars Fosdal 1786 Posted November 27, 2023 @corneliusdavid I replaced shortest with most readable years ago. 😛 1 1 Share this post Link to post
corneliusdavid 209 Posted November 27, 2023 2 minutes ago, Lars Fosdal said: I replaced shortest with most readable years ago I agree it's not near as readable. But it was sure fun to see if I could do it! 2 Share this post Link to post
Uwe Raabe 2051 Posted November 27, 2023 It could be even shorter: Result := MyStr.Remove(MyStr.IndexOf('<')).Trim; No need to check for existence as the internally called _UStrDelete already handles that case pretty well. 5 Share this post Link to post
corneliusdavid 209 Posted November 27, 2023 6 hours ago, Uwe Raabe said: No need to check for existence as the internally called _UStrDelete already handles that case pretty well. Ah Yes! I love it! Share this post Link to post
Lars Fosdal 1786 Posted November 27, 2023 6 hours ago, Uwe Raabe said: It could be even shorter: Result := MyStr.Remove(MyStr.IndexOf('<')).Trim; No need to check for existence as the internally called _UStrDelete already handles that case pretty well. Ok, that is pretty neat! Share this post Link to post