Manipulating Arrays of Characters

Hi,

I would like to program the following in Delphi, but please only write algorithms as I would like to learn the programming language myself.

The following could held in an array of characters called 'names':

'Michael James Jones'

I would like it to be output in the format:

Jones,M.J.

There doesn't necessarily have to be a middle name but there will always be a forename and a surname.

Many thanks.
WilliamIMSAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

mikelittlewoodCommented:
This would be a lot easier to do if you were not using an array and just using a standard string.
If you would like an example using a string I can.
0
geobulCommented:
Hi,

Make a function that accepts names as parameter

1. Initialize three variables to empty string: result, surname and initials
2. Assign names to  a local variable 'fullname'
2. Get the surname from fullname
  - get the position of the last ' ' to 'i' variable and copy from i + 1 to surname var
3. Delete the surname from fullname
  - copy from the beginning of fullname to i - 1 to fullname var
4. Get the initials
  repeat
    initials := initials + <FirstCharOf(fullname)> + '.';
    get the position of the first ' ' to i
    if i > 0 then
       delete the first name from fullname var (copy from i + 1 to the end)
  until i = 0
5. set the final result
  result := surname+','+initials;

Regards, Geo
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
mikelittlewoodCommented:
This would be a string version where sName is the supplied name

  // get the first initial
  sFirst := sName[1];
  // strip off the first word in the string
  sName := Copy(sName, Pos(' ', sName)+1, Length(sName));
  // check the index for a second space
  if Pos(' ', sName) > 0 then
  begin
    // grab the middle initial
    sMiddle := sName[1];
    // strip off the next word
    sName := Copy(sName, Pos(' ', sName)+1, Length(sName));
  end;
  // last word is the surname
  sSurname := sName;
  // build your final display string
  sName := sSurname + ',' + sFirst + '.' + sMiddle + '.';

I wait to see if someone shows an array version
0
Cloud Class® Course: Microsoft Windows 7 Basic

This introductory course to Windows 7 environment will teach you about working with the Windows operating system. You will learn about basic functions including start menu; the desktop; managing files, folders, and libraries.

mikelittlewoodCommented:
ooo just re-read your question ... sorry if I gave too much info  :o/
0
WilliamIMSAuthor Commented:
Hi Mikelittlewood, if you could write an algorithm that uses a string that would be great.

Cheers.
0
kretzschmarCommented:
usual a string is per definition an array of char which begins with the index 1

but to keep near on your question

function get_formated_name(CharArr : Array of Char) : String;
var
  onFirst, getNext : boolean;
  si,se,i : integer;
begin
  result := '';
  si := low(CharArr);  //usual allways 0
  se := high(CharArr);
  onFirst := True;
  getNext := false;
  i := si;
  while i < se do
  begin
    if (CharArr[i] <> ' ') and (onFirst) then
      result := result + CharArr[i]
    else
      if (CharArr[i] = ' ') and (onFirst) then
      begin
        result := result + ',';
        onFirst := False;
        getNext := True;
      end
      else
        if (CharArr[i] = ' ') and (not onFirst) then
          getNext := True
        else
          if (CharArr[i] <> ' ') and (getNext) then
          begin
             result := result + CharArr[i]+'.';
             getNext := False;
         end;
    inc(i);
  end;
end;

just from head -> means not tested and typos possible

meikl ;-)


0
kretzschmarCommented:
for a string:
just replace this first part:

function get_formated_name(CharArr : string) : String;
var
  onFirst, getNext : boolean;
  si,se,i : integer;
begin
  result := '';
  si := 1;
  se := lengthCharArr);
....

but of course using pos and copy is more elegant

just from head -> means not tested and typos possible

meikl ;-)
0
mikelittlewoodCommented:
kretzschmar your result will give Michael,J.J.
0
WilliamIMSAuthor Commented:
Thank you all for your help but I'm trying not to look at delphi code, I want to use an algorithm!!
0
mikelittlewoodCommented:
ok Im not sure what you need from me without me actually writing some code down to do it.
Why do you want to use an algorithm? there are much cleaner quicker methods you can use.
0
geobulCommented:
See mine only. It's just an algorithm :-)
0
kretzschmarCommented:
oops, missed the input ;-))
but well, he needs an algorithm ... whatever he mean, don't know

well another try

//this simple function returns the first part as result, and shorten the given string
//for next item simple call again
//if there are no items, then the given string becomes empty
function SplitStr(Var AString : String; ADelim : String) : String;
var APos : Integer;
begin
  Result := '';
  APos := Pos(ADelim,AString);
  if APos > 0 then
  begin
    Result := Copy(AString,1,APos-1);
    AString := copy(Astring,APos+length(Adelim),MaxLongInt);
  end
  else
  begin
    Result := AString;
    AString := '';
  end;
end;

//a usage sample
procedure TForm1.Button1Click(Sender: TObject);
var s : String;
begin
 ListBox1.Clear;
 s := edit1.text;
 while s <> '' do
   listbox1.items.add(SplitStr(s,edit2.text));
 showmessage('This is what you need:'+#10+
             listbox1.items[2]+','+
             listbox1.items[1][1]+'.'+
             listbox1.items[0][1]+'.');
end;

meikl ;-)
0
mikelittlewoodCommented:
ok here is my attempt at an algorithm description I guess.
This is along the lines of the one geobul gave I think, and Im sure he is describing a string checking one.

1) Have a function that passes in a string parameter (sName) and returns a string

2) Create 2 string variables, 1 for the initials (sInitials), 1 for the surname (sSurname)

3) Get the first character of the string and save as the initial variable with a '.' after it.

4) Get the index position of the first space and copy from index+1 to the end of the end of the string to strip off the first word.

5) Check if another space exists in the string. If a space exists then repeat steps 3 and 4 but add the character and '.' onto the previous sInitials variable.  

6) Then all you are left with is the surname.


0
MinesCommented:
variables--->
Names     : array[size]of string;      {Original Names List}
NameParts : array[1..3]of string[20];         {3 Name Parts}
NameString: string;                  {Temporary Name Holder}
         x: byte;                                  {Counter}
         i: byte;                    {Total # of name parts}
constants--->
const cSpace:  string[1] = (' ');              {Blank Space}

begin
   while {Start Loop with Name[#] List}
   begin
      i:= 0;                         {Initialize Name Parts}
      for x:=1 to 3 do
          NameParts[x]:= '';

      NameString:= Names[#];         {'Michael James Jones'}
      while(pos(cSpace,NameString))>0 do
      begin
         inc(i);        {Obtain First and Middle Name Parts}
         delete(NameString, 1, pos(cSpace, NameString));
      end;

      NameString:= Names[#];         {'Michael James Jones'}
      for x:= 1 to i do {First and Middle Name if Available}
      begin
         NameParts[x]:= NameString[1]+'.';
         delete(NameString, 1, pos(cSpace, NameString));
      end;
      NameParts[3]:= NameString+',';             {Last Name}

      NameString:='';           {Prepare Final Desired Name}

      NameString:= NameParts[3];
      for x:=1 to 2 do  {Add First and Middle Name if exist}
         if length of NameParts[x]>0 then
            NameString:= NameString+NameParts[x]

      {Get the Next Name on the List}
   end;
end;
0
geobulCommented:
What I gave is just an algorithm. Do not think for operators as they are in Delphi. There is no difference in the algorithm what datatypes will be used - string or array of char or something else. Actually Delphi string and array of char types are assignment compatible (with explicit typecasting):

StringVar := string(ArrOfCharVar);

And my algorithm will work with more than one middle name ;-)

I can post all the code immediately because I already have it. Or the necessary functions, at least, like 'Getting the last space occurance', 'copying a part of array somewhere else', 'deleting a part of array', etc.

Regards, Geo
0
aikimarkCommented:
1. Use the built-in parsing facilities of a TStringList object to break up the string into its space-delimited words.
2. Programmatically determine the last word from the parsed output.
3. Initialize the output string to the entire last word concatenated with a comma character
4. Loop through the first through next-to-last words in the string from the parsed output, concatenating the first character of the word and a period character to the end of the output string.

I hope this is algorithmic enough, but still containing clues for your Delphi learning enjoyment.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Delphi

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.