Thread: finding strings in strings

  1. #1
    Registered User
    Join Date
    Dec 2002
    Posts
    21

    Angry finding strings in strings

    i've been working on this project for the past few days and i cant seem to get it to work...

    the function find_word is supposed to determine if one character string exists inside another string...so far it works, only if the the first word entered doesnt have double letters...

    for example...if the first word is ''bookkeeper'', and the word you are looking for is ''keep'', my function won't find it because it only checks ''bookkeeper'' beginning with the first ''k''.

    how do i get my program to work, even with words with double
    letters...any help will be greatly appreciated

    Code:
    #include <stdio.h>
    			/* Function prototypes */
    int find_word ( char word[], char to_find[] ) ;
    int string_compare ( char compare[], char to_find[] ) ;
    void get_string( char buffer[], int size ) ;
    
    const int MAX = 30 ;		/* Max size of array */				
    /*
    Name		:	get_string - Allows the user to input a string.
    Parameters	:	buffer     - The input string.
    */
    void get_string( char buffer[], int size )
    {
     	char character;
     	int j = 0;		
    
     	do									/* Get a character until newline or 		*/
     	{									/* we run out of characters.				*/
    		character = getchar() ;
    		buffer[j] = character ;
    		++j;
    	}
    	while ( character != '\n' && j < size ) ;
    	
    	while ( character != '\n' )			/* Get rid of extra characters.				*/
    		character = getchar() ;
    
    	buffer[j - 1] = '\0' ;				/* Replace newline with the null-byte.		*/
    }
    
    
    void main ( void )
    {
    	char word[ MAX ] ;						/* Word to search */
    	char to_find[ MAX ] ;					/* Word to search for */
    	int found_word ;						/* Flag */
    
    	printf( "Enter a word\t    : " ) ;		/* Prompt user to enter a word */
    		get_string( word, MAX ) ;			/* Get the word */
    
    	printf( "Enter another word  : " ) ;	/* Prompt user to enter another word */
    		get_string( to_find, MAX ) ;		/* Get the word */
    											/* Check if the word to find is in the first word */
    	found_word = find_word( word, to_find ) ;
    
    	if( found_word == -1 )					/* If the word isn't found, display the results */
    		printf( "\n%s was not found in %s.\n", to_find, word ) ;
    	else									/* If it is found, display the index found at */
    		printf( "\n%s was found beginning at index %d.\n", to_find, found_word ) ;
    }
    
    /*
    Parameters	:	word[] - The word to search
    			:	to_find[] - The word to search for
    */
    int find_word ( char word[], char to_find[] )
    {
    	int i, j = 0 ;							/* Loop counters */
    	char compare[ MAX ] ;					/* Word to compare to to_find */
    	int are_equal ;							/* Flag */
    
    	for( i = 0 ; word[ i ] != '\0' ; i++ )	/* Cycle through the array looking for the */
    		if( to_find[ j ] == word[ i ] )		/* first letter of the word to_find. */
    		{									/* If the letter is found, */
    			for( j = 0 ; to_find[ j ] != '\0' ; j++ )	/* copy the dimension of elements of to_find in */
    				compare[ j ] = word[ i + j ] ;			/* word to compare. */
    
    			compare[ j ] = '\0' ;
    
    			are_equal = string_compare( compare, to_find ) ;
    
    			if( are_equal == 0 )
    				return ( -1 ) ;
    			else
    				return ( i ) ;
    		}
    
    }
    				
    /*
    Parameters		: word, string2 - The strings to compare.
    Returns   		: 1 if the strings are equal, 0 if not.
    */
    int string_compare ( char compare[], char to_find[] )
    {
    	int j = 0 ; 							/* Loop counter. */
    	int are_equal ;							/* Flag. */
    											/* Compare the strings. */
    	while ( compare[j] == to_find[j] && compare[j] != NULL && to_find[j] != NULL )
    		++j ;
    
    	if ( compare[j] == NULL && to_find[j] == NULL )
    		are_equal = 1 ;						/* If we've made it to the end of */
    	else									/* both strings, they're equal.	*/
        	are_equal = 0 ;						/* Otherwise, they're not. */
    
    	return ( are_equal ) ;					/* Return to main. */
    }

  2. #2
    Registered User
    Join Date
    Dec 2002
    Posts
    21
    no i am not ''writing this for fun.'' i am writing this the way my teacher specified, so i cant use string.h or strstr( );

    my teacher tends to make us do things the hard way
    Watshamacalit

  3. #3
    Registered User
    Join Date
    Dec 2002
    Posts
    21
    ok...that doesnt work...it still says ''keep'' is not in ''bookkeeper''
    Watshamacalit

  4. #4
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    post a section of your latest code.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  5. #5
    Registered User
    Join Date
    Dec 2002
    Posts
    21

    latest code

    my code is still the same as the above...i can't figure out how to get it to work... my problem is in the following function

    Code:
    /*
    Parameters	:	word[] - The word to search
    			:	to_find[] - The word to search for
    */
    int find_word ( char word[], char to_find[] )
    {
    	int i, j = 0 ;							/* Loop counters */
    	char compare[ MAX ] ;					/* Word to compare to to_find */
    	int are_equal ;							/* Flag */
    
    	for( i = 0 ; word[ i ] != '\0' ; i++ )	/* Cycle through the array looking for the */
    		if( to_find[ j ] == word[ i ] )		/* first letter of the word to_find. */
    		{									/* If the letter is found, */
    			for( j = 0 ; to_find[ j ] != '\0' ; j++ )	/* copy the dimension of elements of to_find in */
    				compare[ j ] = word[ i + j ] ;			/* word to compare. */
    
    			compare[ j ] = '\0' ;
    
    			are_equal = string_compare( compare, to_find ) ;
    
    			if( are_equal == 0 )
    				return ( -1 ) ;
    			else
    				return ( i ) ;
    		}
    
    }
    and...i would use the int main( void ) but...my teacher is a void main (void) 'er and he doesnt like us to use the int main prototype
    Watshamacalit

  6. #6
    Registered User
    Join Date
    Nov 2002
    Posts
    491
    I didn't really read your code, it seemed a bit too long for something like this. The basic idea is relatively simple:

    1) Iterate through the string until findword[0] == searchstring[i]
    2) Check to see if the rest of findword is in searchstring[i...]
    3) If not, go back to findword[0] and continue at searchstring[i+1]
    4) If yes, return TRUE or what not.

  7. #7
    Registered User
    Join Date
    Dec 2002
    Posts
    21
    Originally posted by orbitz
    The basic idea is relatively simple:
    yes i'm sure it is very simple for a more advanced programmer than i. sometimes i just fail to grasp these simple concepts

    Originally posted by orbitz
    2) Check to see if the rest of findword is in searchstring[i...]
    right...i know that but i cant seem to figure out how to write that in my code...
    Watshamacalit

  8. #8
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Use strstr to serach one string for a sub string.

    Quzah.
    Hope is the first step on the road to disappointment.

  9. #9
    Registered User
    Join Date
    Dec 2002
    Posts
    21
    Originally posted by watshamacalit
    i am writing this the way my teacher specified, so i cant use string.h or strstr( );

    my teacher tends to make us do things the hard way
    Watshamacalit

  10. #10
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    Code:
    #define FOUND     1
    #define NOT_FOUND 0
    
    static int ncmp ( char *a, char *b, int len )
    {
      for ( ; *a == *b; a++, b++ ) {
        if ( --len == 0 )
          return FOUND;
      }
    
      return NOT_FOUND;
    }
    
    static int search ( char *text, char *pat, int len )
    { 
      char *start = text;
    
      for ( ; *text != '\0'; text++ ) {
        if ( ncmp ( pat, text, len ) == FOUND ) 
          return text - start;
      }
        
      return NOT_FOUND;
    }
    -Prelude
    My best code is written with the delete key.

  11. #11
    Registered User
    Join Date
    Nov 2002
    Posts
    491
    right...i know that but i cant seem to figure out how to write that in my code...
    So don't write it in your code just yet.

    People have the awful tendency of thinking simply because they are programming that tasks/problems become exponetially more difficult.

    Look at the task from how you do it in real life, and then apply it to your program. Think about the problem before you being writing C code.

    The methods are almost the same, you are simply translating the thoughts do a specific language. Do not simply jump into a problem and start typing. Think before you type.

  12. #12
    Registered User
    Join Date
    Dec 2002
    Posts
    21

    yes...

    Originally posted by orbitz
    So don't write it in your code just yet.

    The methods are almost the same, you are simply translating the thoughts do a specific language. Do not simply jump into a problem and start typing. Think before you type.
    yes, i always do psudocode, preliminary code work, b4 i start any of my programs...i wrote it out on paper but my mind cant seem to translate it from english to c...thats why i came to the board and posted my problem...because i've tried and tried and tried again but i cant get it to work
    Watshamacalit

  13. #13
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    Your doing fine. Just keep at it. One suggestion I have is to print every single step of the way, every time through a loop, etc. That way, you can see how the code responds to the input and spot the problem quickly. It's hard when we are new to programming to wrap our minds around the problem, in time though it will of course become much simpler to you. Just practice constantly.


    Anyway, here is a simple example of an array-based substring search. The general idea is to set up two loops, the first which restarts the search at the next position of the input string, and the second loop which does the actual searching.

    When we reach the end of the search string, we know the search was a success. When we reach the end of the input string, we know that there is nothing left to search.


    Code:
    /* function returns 0-based index of substring or -1 on error */
    
    int find_string(const char * input, const char * find){
    
     int i, f, start = 0;
     int iLen = strlen(input);
     int fLen = strlen(find);
    
       while(1)
      {
            if(start == iLen) //...nothing left to search
           {
            break;  // exit completely
           }
    
       i = start, f = 0;  // reset
    
             while(1)
            {
                   if(find[f] == 0)//...end of "find" == success
                  {
                   return start;
                  }
                   else if(find[f] != input[i])
                 {
                  break;  // no match here
                 }
    
             f++, i++;
            }
    
      ++start;  // inch through input string
      }
    
     return -1;
    }
    
    
    
    
    
    int main(){
     char string[] = "Jacobs Ladder";
     char find[] = "der";
     int result = find_string(string, find);
    
        if(result == -1)
          printf("Not Found");
        else
          printf("Found at position %i", result);
    
     getch();
    
     return 0;
    }



    I hope that helps. Good luck.
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  14. #14
    Registered User
    Join Date
    Dec 2002
    Posts
    21

    Cool thanks!!

    your code helped greatly...i just made a few changes so it could handle user input... but theres one thing i dont understand... why did u use while(1)...i've never seen it like that nor have we learned that in class yet...
    Watshamacalit

  15. #15
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    That's just a way to set up an infinite loop. Any true statement works, like while(7==7), etc...

    I just thought the code looked clearer that way, but usually, if it makes sense to, you should put the appropriate conditional there. For instance, the first loop would be better off as

    while(start != iLen)

    ...
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Strings Program
    By limergal in forum C++ Programming
    Replies: 4
    Last Post: 12-02-2006, 03:24 PM
  2. Programming using strings
    By jlu0418 in forum C++ Programming
    Replies: 5
    Last Post: 11-26-2006, 08:07 PM
  3. Help with finding the intersection of 2 strings
    By hay_man in forum C++ Programming
    Replies: 5
    Last Post: 09-30-2006, 06:30 PM
  4. Finding a string's pixel width
    By @nthony in forum Windows Programming
    Replies: 2
    Last Post: 08-03-2006, 02:11 AM
  5. Finding similar words from 2 strings
    By lzhaol in forum C++ Programming
    Replies: 7
    Last Post: 02-26-2006, 01:45 AM