Thread: pattern matching in strings

  1. #1
    Registered User
    Join Date
    Jun 2009
    Location
    US of A
    Posts
    305

    pattern matching in strings

    I am trying to solve a problem wherein if a pattern appears in a string i can figure it out and tell the position where it is occuring. The thing is that what is happening is that for example i have a original string as "Rohan" then i am trying to traverse this string. And so i increment the pointer that is pointing to it. And this should enable me to traverse the string while the end of the string is not reached. But in the current set up i get stuck at o and it does not seem to move ahead.

    [insert]
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int search (char *s, char *p);
    
    int main(void){
    	
    	//char *s, *p;
    	char s1[] = "NagpurKicit";
    	char s2[] = "Kicit";
    	int pos;
    
    	pos = search(s1, s2);
    	return 0;
    }
    
    int search(char *s, char *p){
    	
    	int i,slen, plen, posn = 0, lenc = 0;
    	char ss, pp;
    	int found;
    	char *sc, *pc;
    	sc = s;
    	pc = p;
    	slen = strlen(s);
    	plen = strlen(p);
    	ss = *s; 
    	pp = *p;
    
    	printf("\n %c", ss);
    	printf("\n %c", pp);
    
    	printf("\n %d", slen);
    	printf("\n %d", plen);
    
    	for(i = slen ; s > 0; s--)
    	{
    
    		posn++;
    
    		if(ss == pp)
    		{	
    			s++;
    			p++;
    			ss = *s;
    			pp = *p;
    			++lenc;
    			if(pp == '\0')
    			{
    				if(lenc == plen)
    					found = 1;
    				break;
    			}
    
    			if(found == 1)
    				break;
    		}
    		s++;
    		ss = *s;
    	}
    
    	posn = posn - lenc;
    	return posn;
    }
    The code is not working right now it has lots of glitches which i am trying to sort out. So please ignore that.

  2. #2
    Registered User
    Join Date
    Mar 2003
    Location
    UK
    Posts
    170
    The 'for' loop will loop forever, i is set to slen but not used, but then incrementing and decrementing the s pointer on each loop.
    Code:
    for(i = slen ; s > 0; s--)
    {
    	s++;
    }
    Have a look at using the strstr() function.
    Last edited by Scarlet7; 08-11-2009 at 03:56 AM.

  3. #3
    Registered User
    Join Date
    Jun 2009
    Location
    US of A
    Posts
    305
    Thanks, i got it working now.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. matching of names in 2d array of strings...
    By roaan in forum C Programming
    Replies: 6
    Last Post: 07-25-2009, 09:59 AM
  2. Replies: 5
    Last Post: 06-01-2009, 07:54 PM
  3. Replies: 5
    Last Post: 05-25-2004, 04:36 PM
  4. Going out of scope
    By nickname_changed in forum C++ Programming
    Replies: 9
    Last Post: 10-12-2003, 06:27 PM
  5. pattern matching
    By ahahplz in forum C Programming
    Replies: 5
    Last Post: 02-07-2003, 07:15 PM