Thread: Comparing Strings

  1. #1
    Registered User
    Join Date
    May 2017
    Posts
    6

    Comparing Strings

    The task is following:
    Write a function
    Code:
    int name(char *s1, char *s2)
    that returns the position of the first occurrence of string s2 in string s1. The positions are numbered from 0 to strlen(s1)-1. If s1 has szero length or s2 has zero length or s2 cannot be found in s1 the function must return -1.

    Write a main program that prompots for s1 and s2 and prints them along with the result of calling Locate with them.

    Assume a maximal string length of 100 in the main program; in the function, the string lengths schould be limited by the maximal positive value of int only.
    BTW: String-functions are not allowed to use.

    1. How would you recommend to do fgets error-handling?

    The task said, that the main program should be limited with a string-length of 100, so I used fgets, because it does not matter how much you put in, the string will always be stored with the count of characters you give to fgets(). The rest will stay in the buffer and excuted in the next round, but to prevent this I used fseek to let the File Pointer point to the end of the input buffer. I've also tried to use
    Code:
    while ((c = getchar()) != '\n' && c != EOF) {}
    , but this will let you wait till a new input from the keyboard.

    Which brings me to this question:
    2. Can you actually use this while to clear the buffer without waiting for a new input? Is the solution fseek okay, because it only puts the file pointer at the end and do not delete the input buffer?

    3. Are there even certain cases in which you only can use s[i] or *(s+i)? (when s is declared as a pointer)

    4. What else do you think can I improve?


    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <limits.h>
    
    int Locate(char *s1, char *s2);
    
    int StrCmp(char *s1, char *s2);
    int StrLength(char *s);
    
    int main(void)
    {
      enum { MAX_LENGTH = 5 };
    
      char s1[MAX_LENGTH];
      char s2[MAX_LENGTH];
    
      int s1Len;
      int s2Len;
    
      printf("1. string (max. 100): ");
    
      while(fgets(s1, MAX_LENGTH, stdin) != NULL)
      {
        fseek(stdin, 0, SEEK_END);
        s1[s1Len=StrLength(s1) - 1] = '\0';    
          
        printf("2. string (max. 100): ");
        if (fgets(s2, MAX_LENGTH, stdin) == NULL)
        {
          printf("\nError, string s2 couldn't be read properly.\n");
          exit(EXIT_FAILURE);
        }
    
        fseek(stdin, 0, SEEK_END);
        s2[s2Len=StrLength(s2) - 1] = '\0';
        
        if (s1Len > 0 && s2Len > 0)
        {
          printf("\nPosition of the first occurence of ");
          printf("String 2: ");
          fputs(s2, stdout);
    
          printf(" in ");
          printf("String 1: ");
          fputs(s1, stdout);
          
          printf(" : %d\n", Locate(s1,s2));
        }
        else // empty input
        {
          printf("\nError, empty input.\n");
        }
    
        printf("\n1. string (max. 100): ");
      }
    
      printf("\nError, string s1 couldn't be read properly.\n");
    
      return 0;
    }
    
    /*looks for first occurence of s2 in s1*/
    int Locate(char *s1, char *s2)
    {
      int i=0;
      int s1Len;
      int s2Len;
    
      if ((s1Len=StrLength(s1)) <= INT_MAX && (s2Len=StrLength(s2)) <= INT_MAX)
      {
        if (s1Len < s2Len) return -1;
    
        while (s1[i] != '\0')
        {
          if (StrCmp(s1 + i, s2))
          {
            return i;
          }
          i++;
        }
    
        return -1;
      }
      else
      {
        printf("Error, input too long!");
        exit(EXIT_FAILURE);
      }
    }
    
    /*compares strings whereby their lengths are "length of s2
    2*/
    int StrCmp(char *s1, char *s2)
    {
      int i = 0;
      int eq = 0;
    
      while (s2[i] != '\0')
      {
        if (s1[i] == s2[i])
        {
          eq++;
        }
        i++;
      } 
      
      if (i == eq) //check if s1 and s2 are identical (i (=eq) characters)
      {
        return 1; // identical
      }
      else 
      {
        return 0; // not identical
      }
    }
    
    /*counts string length of s*/
    int StrLength(char *s)
    {
      int cnt=0;
    
      while (s[cnt] != '\0')
      {
        cnt++;
      }
    
      return cnt;
    }

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by quarkse
    1. How would you recommend to do fgets error-handling?

    The task said, that the main program should be limited with a string-length of 100, so I used fgets, because it does not matter how much you put in, the string will always be stored with the count of characters you give to fgets(). The rest will stay in the buffer and excuted in the next round, but to prevent this I used fseek to let the File Pointer point to the end of the input buffer.
    Don't use fseek on stdin. Rather, call fgets once, and search the string for '\n'. If it exists, replace it with '\0'; if it does not exist, then you can keep reading from stdin and discard characters until '\n' is encountered.

    Quote Originally Posted by quarkse
    2. Can you actually use this while to clear the buffer without waiting for a new input? Is the solution fseek okay, because it only puts the file pointer at the end and do not delete the input buffer?
    I would not recommend using fseek on stdin because I do not think it is guaranteed to work as expected with ordinary files.

    Quote Originally Posted by quarkse
    3. Are there even certain cases in which you only can use s[i] or *(s+i)? (when s is declared as a pointer)
    They are equivalent, so unless you have special reason to choose *(s+i), you should prefer the more readable s[i].
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Comparing Python strings to C strings
    By hinesro in forum C Programming
    Replies: 0
    Last Post: 11-29-2015, 09:14 PM
  2. Comparing strings
    By JohnDeon in forum C Programming
    Replies: 3
    Last Post: 11-22-2011, 07:19 PM
  3. comparing strings.
    By goran00 in forum C Programming
    Replies: 3
    Last Post: 04-20-2008, 08:18 AM
  4. [HELP] about comparing between two strings...
    By kyaky in forum C++ Programming
    Replies: 12
    Last Post: 08-06-2007, 10:12 AM
  5. comparing strings
    By gammacad in forum C Programming
    Replies: 3
    Last Post: 06-15-2002, 06:07 PM

Tags for this Thread