Announcement

Collapse
No announcement yet.

How to read longer name

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • How to read longer name

    How do I read a list of name, and then tell which one is
    the longest. And, how can I get the longest number of letters, in a
    name, changed to the Name of the letters, example: Dan 3.

    -------------
    Kro121
    Kro121

  • #2
    Reading the names is simple, but how it is done depends on where the list resides. For example, if the list is in a disk (text)file, with one name per line, then the following code will work fine:

    'names.txt would loook like this:
    DAN
    BRUCE
    DAVE
    SAMSON
    GODFREY
    Al
    ...etc


    DIM A$(1:1000) ' maxmimum 1000 names
    x% = FREEFILE
    OPEN "NAMES.TXT" FOR INPUT AS #x%
    y% = 0
    WHILE NOT EOF(x%)
    INCR y%
    LINE INPUT #x%, A$(y%)
    WEND
    CLOSE #1

    TO sort the list into alphanumeric order is simple too:

    ARRAY SORT A$() FOR y%

    Now, find the longest name (in characters).

    z% = 0
    FOR x% = 1 to y%
    z% = MAX%(z%, len(A$(x%))
    NEXT x%

    At this point, z% contains the array subscript number of the name with the most letters.

    PRINT "The longest name is " + A$(z%) + " and it is " + LEN(A$(z%)) + " characters long."

    I've kept the example code very simple here. In a real application you may want to combine the length-checking code into the file-read loop. Also, I've not added any error checking to verify the file I/O operations (or is the names list file even exists!), or checked if the names list exceeds the limit of the array - in a real application all of these things would need to be taken into account. Also, the code would need to handle the situation where no names existed in the list...

    Programming certainly is fun! I hope this helps!


    ------------------
    Lance
    PowerBASIC Support
    mailto:[email protected][email protected]</A>
    Lance
    mailto:[email protected]

    Comment


    • #3
      Now, find the longest name (in characters).

      Code:
      z% = 0
      FOR x% = 1 to y%
        z% = MAX%(z%, len(A$(x%))
      NEXT x%
      At this point, z% contains the array subscript number of the name with the most letters.
      Actually, at this point z% will contain the length of the longest
      string, not its subscript number. This will get the actual subscript
      number:

      Code:
      z% = 1
      FOR x% = 1 to y%
       IF LEN(A$(x%)) > LEN(A$(z%)) THEN z% = x% 
      NEXT x%

      ------------------

      Comment


      • #4
        Oops! Well spotted! I shouldn't have written that code on-line...

        ------------------
        Lance
        PowerBASIC Support
        mailto:[email protected][email protected]</A>
        Lance
        mailto:[email protected]

        Comment

        Working...
        X