?
Solved

Manipulating Arrays of Characters

Posted on 2005-03-01
18
Medium Priority
?
198 Views
Last Modified: 2010-04-05
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.
0
Comment
Question by:WilliamIMS
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 3
  • 3
  • +3
18 Comments
 
LVL 15

Expert Comment

by:mikelittlewood
ID: 13428908
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
 
LVL 17

Accepted Solution

by:
geobul earned 400 total points
ID: 13429151
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
 
LVL 15

Assisted Solution

by:mikelittlewood
mikelittlewood earned 400 total points
ID: 13429172
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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 15

Expert Comment

by:mikelittlewood
ID: 13429180
ooo just re-read your question ... sorry if I gave too much info  :o/
0
 

Author Comment

by:WilliamIMS
ID: 13429183
Hi Mikelittlewood, if you could write an algorithm that uses a string that would be great.

Cheers.
0
 
LVL 27

Expert Comment

by:kretzschmar
ID: 13429218
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
 
LVL 27

Expert Comment

by:kretzschmar
ID: 13429249
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
 
LVL 15

Expert Comment

by:mikelittlewood
ID: 13429430
kretzschmar your result will give Michael,J.J.
0
 

Author Comment

by:WilliamIMS
ID: 13429456
Thank you all for your help but I'm trying not to look at delphi code, I want to use an algorithm!!
0
 
LVL 15

Expert Comment

by:mikelittlewood
ID: 13429532
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
 
LVL 17

Expert Comment

by:geobul
ID: 13429571
See mine only. It's just an algorithm :-)
0
 
LVL 27

Assisted Solution

by:kretzschmar
kretzschmar earned 400 total points
ID: 13429670
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
 
LVL 15

Expert Comment

by:mikelittlewood
ID: 13430223
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
 

Assisted Solution

by:Mines
Mines earned 400 total points
ID: 13431381
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
 
LVL 17

Expert Comment

by:geobul
ID: 13432251
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
 
LVL 46

Assisted Solution

by:aikimark
aikimark earned 400 total points
ID: 13435648
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

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Creating an auto free TStringList The TStringList is a basic and frequently used object in Delphi. On many occasions, you may want to create a temporary list, process some items in the list and be done with the list. In such cases, you have to…
Introduction I have seen many questions in this Delphi topic area where queries in threads are needed or suggested. I know bumped into a similar need. This article will address some of the concepts when dealing with a multithreaded delphi database…
If you’ve ever visited a web page and noticed a cool font that you really liked the look of, but couldn’t figure out which font it was so that you could use it for your own work, then this video is for you! In this Micro Tutorial, you'll learn yo…
This is my first video review of Microsoft Bookings, I will be doing a part two with a bit more information, but wanted to get this out to you folks.
Suggested Courses
Course of the Month11 days, 13 hours left to enroll

752 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question