1

I know there a many ways to split a String, so that you'll get a StringList. But my problem is that I want to split every character of the string.

That means the following String:

'That is my Example String'

should be converted to an array/Stringlist or what so ever:

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
T h a t   i s   m y    E  x  a  m  p  l  e     S  t  r  i  n  g

In Perl or Java the delimiter field of the split-function is just be let empty like for example:

Perl: @string=split("",$string);
Java: String[] myStringArray=myString.split("");

What would be the best way for Delphi to manage this?

user3133542
  • 1,695
  • 4
  • 21
  • 42

1 Answers1

9

Usually there is no real need for such function in Delphi, because Delphi string behaves as char array, every element is accessible by index, and char is assignment compatible with string. Thereby you can use s[i] instead of splited[i] in almost all cases.

If you do need special function to fill a list, it may look like

procedure SplitStringEx(const s: string; Splitted: TStrings);
var
  i: Integer;
begin
  Splitted.Clear;
  for i := 1 to Length(s) do
     {possible variant for fresh Delph versions 
     to take zero-based strings into account:}
  //for i := Low(s) to High(s) do  
    Splitted.Add(s[i])
end;

usage
  SplitStringEx('abc', Memo1.Lines);
MBo
  • 77,366
  • 5
  • 53
  • 86
  • 1
    Only note that the first char is at index 1. `Low(s)` wont even compile in D5 (not tested in later versions). better use `1..Lenth(s)`. `Splitted.BeginUpdate/EndUpdate` is also a good idea. – kobik Aug 24 '14 at 07:03
  • @kobik I've written `Low` because of possibility to use zero-based numeration in fresh Delphi versions. But you're right that 1-based approach would be better for unexperienced user. – MBo Aug 24 '14 at 09:01
  • OK, and I'm adding [this as a reference](http://stackoverflow.com/questions/19488010/how-to-work-with-0-based-strings-in-a-backwards-compatible-way-since-delphi-xe5). – kobik Aug 24 '14 at 09:23