Thread: Finding substrings with arrays...need help

  1. #1
    Registered User
    Join Date
    Feb 2008
    Posts
    116

    Finding substrings with arrays...need help

    Write a C program that allows the user to enter two strings s1 and s2 and checks if s2 is a subtring of s1. If this is the case, it reports the index of s1 at which an instance of s2 is present, otherwise it reports that the substring was not found. For example, cat and nate are two subtrings of concatenate. (The only library functions you are allowed to use are printf and fgets). Your program must print appropriate prompts and messages.

    Here is my code so far:

    Code:
    #include <stdio.h>
    
    int main()
    {
    	
    	char s1[6];
    	char s2[6];
    	char temp[255];
    
    	int i,j,k=1;
    	
    
    	printf("\nEnter first string1 (word 5 characters or less): ");
    	fgets(s1, 6, stdin);
    
            gets(temp);
    
    	printf("\nEnter substring to find in string1 (word 5 characters or less): ");
    	fgets(s2, 6, stdin);
    
    	for(i=0; i<6; i++)
    	{
    		for(j=0; j<6; j++)
    		{
    			if(s2[i]==s1[j])
    			{
    				//printf("&#37;c%c\n", s2[i], s1[j]);
    
    				//break;
    			}
    
    			
    		}
    	}
    
    
    	
    
    return(0);
    }

    Right now, I have it so that the user inputs a 5 word character for s1 and s2. I have the for loop as a setup to check if s2 has the same characters as s1. The problem I am having is trying to report that the index of s1 at which an instance of s2 is present, otherwise it not being found...

    I was thinking about trying to use a way to use true and false flags so that if s2 is true (meaning it is present in s1), then it would print a message. If s2 is false (meaning s2 is not present in s1), then it would say substring was not found. I don't understand how to implement it...

    What would be the best way?

    Can anyone help me out??
    Last edited by dcwang3; 02-19-2008 at 05:48 PM.

  2. #2
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Gets is bad: http://cpwiki.sf.net/gets.
    Further, fgets reads the entire line (unless they enter more than 5 chars), so gets is unnecessary.
    For the loop, you should loop the actual length of the string and no more or less, because there may be junk in there (and it will of course react because both strings contains \0 at the end), so use strlen to get the length of the strings.
    As for the logic, one way I see is the make an additional loop inside your if. You could use a flag there as well, that is set to true initially. The loop will check if each subsequent character matches. An example of what I mean:

    If the entered string is: concatenate
    And you search for nate.
    If it finds the 'n', you enter another loop. This will check if the next char is equal to the second character in the string you're trying to match, in this example, 'a'. If it doesn't match, then set flag to false and break loop.
    Then continue for the third character, fourth, and so on .

    Good luck.
    Last edited by Elysia; 02-19-2008 at 01:35 PM.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  3. #3
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    also fgets is not allowed by the assignment
    and sample string concatenate will not pass into the array of 6 characters - so you definitely need larger array for the string to be searched

    in your inner loop note that the searched string could be shorted than 6 characters - fro example 3 like cat - so it will not fill the whole buffer

    And you should break the inner loop as soon as not matched character found - to start checking the next subsequence of characters in the original string

    And if you go to the nul-character of the searched string without breaking the inner loop - you have found your matchand should report the results

    and think about
    concatenate and
    cat
    you will find your match when i == 3
    but you should check in the inner loop
    s1[i] == s2[0] == 'c' (j == 0)
    s1[i+1] == s2[1] == 'a' (j == 1)
    s1[i+2] == s2[2] == 't' (j == 2)

    in your code you are comparing all the characters of the cat-string to the 'c' character of the originat string
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  4. #4
    Registered User
    Join Date
    Oct 2004
    Posts
    151
    Code:
    Find-String(T,P)
    1 nlength(T)
    2 mlength(P)
    3 for s ← 0 to n - m
    4     do if P(1 .. m) = T(s + 1 .. s + m)
    5           then print “Substring found with shift” s
    This pseudocode which I adapted out of a book is an algorithm finds all occurrences of the substring P in the text T. On line 3 we have a for loop that iterates through all possible positions of the text. In line 4 we test whether this position matches by comparing the characters of P and T so that they are all equal (in the real code you'd use another loop).

    Imagine moving a strip of transparent plastic with P written on it over top a piece of paper with T on it, one character at a time, and looking to see if the strings match each time. That's basically how this algorithm works.

  5. #5
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    I don't know why they would restrict the use of all library functions. Obviously, I understand why they wouldn't want you to use functions for string searching and matching, but input functions, such as fgets?

    Anyway, since it says only scanf is allowed, I suggest you read this: http://cboard.cprogramming.com/showp...37&postcount=9
    It touches the topic about reading strings with scanf.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  6. #6
    Registered User
    Join Date
    Feb 2008
    Posts
    116
    oh I'm sorry, scanf is suppose to be replaced with fgets....

  7. #7
    Registered User
    Join Date
    Feb 2008
    Posts
    2
    lol you come on here for every assignment

  8. #8
    Registered User
    Join Date
    Feb 2008
    Posts
    116
    yeah because my professor is stupid and assigns us crazy problems even though he hasn't taught the material....

  9. #9
    uint64_t...think positive xuftugulus's Avatar
    Join Date
    Feb 2008
    Location
    Pacem
    Posts
    355
    Professors rarely do teach material. Outsmart them by **KNOWING** the material. You have a computer, you have google, you have 1 million C tutorials out there. Code, books, algorithms everything. Filter knowledge out of them.
    Imagine that you were in the 60's, and your programming was done in assembler (if you were lucky) or newborn languages that hadn't matured yet. Libraries? No... Books? 1,2 ? The fact that your professor can't teach you, is no excuse. In the year 2008 using it as an excuse is like saying... "Hey i'm hungry but no-one gives me to eat" inside a restaurant full of dishes and without people.
    Code:
    ...
        goto johny_walker_red_label;
    johny_walker_blue_label: exit(-149$);
    johny_walker_red_label : exit( -22$);
    A typical example of ...cheap programming practices.

  10. #10
    Registered User
    Join Date
    Feb 2008
    Posts
    2
    Quote Originally Posted by dcwang3 View Post
    yeah because my professor is stupid and assigns us crazy problems even though he hasn't taught the material....
    I'm not sure. I think Venkat is a good teacher.

  11. #11
    uint64_t...think positive xuftugulus's Avatar
    Join Date
    Feb 2008
    Location
    Pacem
    Posts
    355
    Probably, but most lazy students will blame the teacher to avoid blaming themselves.
    Code:
    ...
        goto johny_walker_red_label;
    johny_walker_blue_label: exit(-149$);
    johny_walker_red_label : exit( -22$);
    A typical example of ...cheap programming practices.

  12. #12
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by xuftugulus View Post
    Professors rarely do teach material. Outsmart them by **KNOWING** the material. You have a computer, you have google, you have 1 million C tutorials out there. Code, books, algorithms everything. Filter knowledge out of them.
    Imagine that you were in the 60's, and your programming was done in assembler (if you were lucky) or newborn languages that hadn't matured yet. Libraries? No... Books? 1,2 ? The fact that your professor can't teach you, is no excuse. In the year 2008 using it as an excuse is like saying... "Hey i'm hungry but no-one gives me to eat" inside a restaurant full of dishes and without people.
    I think that's kind of cheap. If I wanted to learn C or C++ that way, I could just study it myself from home. The point of taking a class is for the teacher to help and actually teach the students and not just throw out assignments and grade. That kindof beats the whole point IMO.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  13. #13
    uint64_t...think positive xuftugulus's Avatar
    Join Date
    Feb 2008
    Location
    Pacem
    Posts
    355
    Quote Originally Posted by Elysia View Post
    The point of taking a class is for the teacher to help and actually teach the students and not just throw out assignments and grade. That kindof beats the whole point IMO.
    Well, i couldn't agree more. But you must admit that education is turning a little bit towards becoming an industry on its own. Nobody is born knowing everything. My point was that usually students fail to see any worth in their tutors guidance. That is wrong, except from the fact that there are so many university teachers out there that just don't do it right. You simply can't cover 600 book pages in a semester completely. Therefore they throw out a couple of slides, and some copy paste lecture and an applicable "assignment"and consider their work done.

    From the point of view of the teacher, it is usually not so easy to handle their situation better. But the student, simply can't always blame the teacher. If you are going to learn something, you'd better have your mind set to do so, instead of spitting out a blant.
    "My teacher is stupid and gives us tough assignments."

    This is not an appropriate thread for such discussion though, and i would prefer if we didn't prolong the subject. I just needed to clarify my point a bit, which was not meant to be insulting, but rather uprising for those that settle with cheap excuses.
    Code:
    ...
        goto johny_walker_red_label;
    johny_walker_blue_label: exit(-149$);
    johny_walker_red_label : exit( -22$);
    A typical example of ...cheap programming practices.

  14. #14
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    "The facts are abundant, the will to seek them out is scarce."

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 10
    Last Post: 04-26-2009, 02:46 PM
  2. Strings and Substrings using arrays
    By dcwang3 in forum C Programming
    Replies: 12
    Last Post: 02-18-2008, 07:28 AM
  3. Finding the sum of even numbers using arrays
    By Fox101 in forum C Programming
    Replies: 7
    Last Post: 12-03-2007, 02:20 PM
  4. Finding and Printing prime numbers using arrays
    By Sektor in forum C++ Programming
    Replies: 5
    Last Post: 12-11-2003, 08:29 PM
  5. Help with finding median with arrays.
    By Niloc1 in forum C Programming
    Replies: 3
    Last Post: 03-26-2002, 03:32 PM