Arrays

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • gwenky
    New Member
    • Feb 2008
    • 10

    Arrays

    Hello,

    I am working on the last peice of my final for my C++ class. I understand the rules about helping with homework, so this is really just a question. If I wanted to find out if my char array[] had all the same character's in the array, what would be the best method for attempting this type of thing.

    So, example:

    char array [];

    user enters: aaaa

    how then, should I proceed to find if all the characters are the same letter?

    I have tried a strcpy and comparison, but obviously that failed as when the user inputted: final
    char array[0] = f was the same as char copy[0] = f

    so my logic is off. Any suggestions or hints?

    Thanks,

    Julie
  • gpraghuram
    Recognized Expert Top Contributor
    • Mar 2007
    • 1275

    #2
    I am not getting ur question fully.
    Do you want to check whether the value in the array is all the same that is all characters are same
    or you want to compare the array with some other array.
    can you brief more

    Raghuram

    Comment

    • Ganon11
      Recognized Expert Specialist
      • Oct 2006
      • 3651

      #3
      Here's a really simple way: If the letters are all the same, then they're all the same as the first one, right?

      So make an array consisting of just the first character repeated to be the same size as the original array. If they are equal, then the first string had all repeating characters. If they aren't equal, then at least one character is different.

      Comment

      • gwenky
        New Member
        • Feb 2008
        • 10

        #4
        Thanks! That is a great idea!

        Julie

        Comment

        • JimbOr
          New Member
          • Mar 2008
          • 1

          #5
          Originally posted by Ganon11
          Here's a really simple way: If the letters are all the same, then they're all the same as the first one, right?

          So make an array consisting of just the first character repeated to be the same size as the original array. If they are equal, then the first string had all repeating characters. If they aren't equal, then at least one character is different.
          That would be a bit 'overkill' don't you think?

          (Note, I've assumed she's talking C style char[] here, as would seem to be the case)

          If she's allowed to use standard string libraries, why not just search for the first occurrence in the array of anything that's not the first character? (strspn)

          If she's not allowed to use standard string libs, then your solution requires she write versions of strlen, memset and strcmp. Why not just compare each array element to the 1st?

          Cheers,
          JimbO

          Comment

          Working...