Jump to content
Henry Olive

Pos, SplitString

Recommended Posts

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
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
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.

  • Thanks 1

Share this post


Link to post

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

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
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!

  • Like 2

Share this post


Link to post

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.

  • Like 5

Share this post


Link to post
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
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×