Thread: Searching an array for another array

  1. #1
    Registered User
    Join Date
    Oct 2003
    Posts
    12

    Searching an array for another array

    I am writing this program to read 2 strings and to check if the 1st string is a sub-string of the 2nd. I need help writing my function that searches string 2 for string 1 and returns the element number of the first match if it is a sub-string and returns -1 if it is not a sub-string. The function declaration I need help with is:

    int str_search(char s1[], int n1,char s2[], int n2);


    Code:
    #include <stdio.h>
    #define maxlen 50
    
    void str_set(char s[], int n, char a);
    void str_set(char s[], int n, char a)
    	{
    		int i=n;
    		for(n=0; n<i; n++)
    			{
    				a=getchar();
    				s[n] = a;
    				if(a == '\n')
    					break;
    			}
    	}
    
    void str_print(char s[], int n);
    void str_print(char s[], int n)
    	{
    		int i=n+1;
    		for(n=0; n<i; n++)
    		{
    			printf("%c", s[n]);
    			if(s[n] == '\n')
    				break;
    		}
    	}
    
    int str_search(char s1[], int n1,char s2[], int n2);
    int str_search(char s1[], int n1,char s2[], int n2)
    	{
    		
    	}
    main()
    
     {
    	char s1;
    	char s3;
    	char s[maxlen]={32};
    	char s2[maxlen]={32};
    	int n;
    	
    
    	printf("Enter string A.\n");
    	str_set(s, maxlen, s1);
    
    	printf("\nEnter string B.\n");
    	str_set(s2, maxlen, s3);
    
    	printf("\nString A:\t");
    	str_print(s, maxlen);
    
    	printf("\nString B:\t");
    	str_print(s2, 40);
    
    	n = str_search(s, 50, s2, 50);
    		if(n == -1)
    		printf("\nString A is not a sub-string of String B.");
    		else
    		printf("\nString A is a sub-string of String B.");
    
    
    
     }

  2. #2
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    I take it you're not allowed to use strstr(), a standard C function that does what you're asking?

    If not, map out the process on paper first, step by step, then translate that to code. A couple of loops should be of use to you.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 07-11-2008, 07:39 AM
  2. Searching between array indicies
    By Asagohan in forum C Programming
    Replies: 7
    Last Post: 04-27-2005, 12:28 AM
  3. Not getting good result searching an array of string.
    By cazil in forum C++ Programming
    Replies: 5
    Last Post: 02-12-2002, 11:24 AM
  4. Searching for multiple items in an array
    By Unregistered in forum C++ Programming
    Replies: 3
    Last Post: 12-04-2001, 03:26 PM
  5. Structure Array searching
    By ling in forum C Programming
    Replies: 4
    Last Post: 10-18-2001, 12:39 PM