String manipulation

This is a discussion on String manipulation within the C Programming forums, part of the General Programming Boards category; Hi, im trying to write a code to find whether one string is inside another string, without using the strstr() ...

  1. #1
    Registered User
    Join Date
    Oct 2007
    Posts
    38

    String manipulation

    Hi, im trying to write a code to find whether one string is inside another string, without using the strstr() library. What I got so far is as follows:

    Code:
    #include <stdio.h>
    int getlength(char[]);
    
    int main() {
    	char str1[] = "This is a string";
    	char str2[] = "str";
    	int len1 = getlength(str1);
    	int len2 = getlength(str2);
    
    	int x, i, j;
    	for (i = 0; i < (len1 - len2); i++) {
    		j = 0;
    		if (str2[j] == str1[i]) {
    			for (j = 1; j < len2; j++) {
    				if (str2[j] == str1[i + j]) x = 0;
    				else x = 1;
    			}
    			if (x == 0) {
    				printf("True!");
    				return 0;
    			}
    		}
    	}
    	printf("False!");
    	return 1;
    }
    /* Get String Length function */
    int getlength(char str[]) {
    	int len = 0;
    	while(str[len] != '\0') len++; return len;
    }
    Although, it seems to work with the current values of char arrays, when I change things around, it doesnt always produce the desired outcome.
    Can anyone please point me to the place that needs to be reviewed?
    Thanx in advance

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,485
    What about using strncmp() and a for loop ?

    What about writing say myStrncmp() and myStrstr() ?
    Just because you're not allowed to use the functions doesn't mean you can write your own similarly named functions, with the same API.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    Registered User
    Join Date
    Oct 2007
    Posts
    38
    What about using strncmp() and a for loop ?
    No, Im not allowed to use any string.h functions

    What about writing say myStrncmp() and myStrstr() ?
    Thats what Im actually trying to do with the code inside main(). Sure, its not a function, but the purpose remains the same...

  4. #4
    Registered User
    Join Date
    Mar 2007
    Posts
    4
    In your second for loop you make x=0 if the characters are same.Assume a case like
    str1[]="this is string"
    str2="srr"
    Lets now analyse it
    if (str2[j] == str1[i + j])

    results of x:
    x=0
    x=1
    x=0
    so whenever u get x=1 u shud break out of the loop.

  5. #5
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,485
    Well writing two functions (of whatever name you would like to call them), each only 5 lines long, is going to result in something a lot easier to think about, and a lot easier to debug.

    When you've got it all working (or even using strncmp() just to prove the point, then writing your own), then you can inline it all in main() if you still want to.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  6. #6
    Registered User
    Join Date
    Oct 2007
    Posts
    38
    Ok, I've rewritten the program... Seems to be working well... Although my function is much longer than 5 lines long... Is there an easier way of doing the same thing with less code?

    Code:
    #include <stdio.h>
    int findstring(char[], char[]);
    
    int main() {
    	char str1[] = "String";
    	char str2[] = "ring";
    
    	int result = findstring(str1, str2);
    	if(result == 1) printf("Not Found");
        else printf("Found");
    }
    /* Check For A String Inside Another String function */
    int findstring(char str1[], char str2[]) {
    	int getlength(char[]);
    	int len1 = getlength(str1);
    	int len2 = getlength(str2);
    	int x, i, j;
    
    	for (i = 0; i < (len1 - len2); i++) {
    		j = 0;
    		if (str2[j] == str1[i]) {
    			for (j = 1; j < len2; j++) {
    				if (str2[j] == str1[i + j]) x = 0;
    				else {
    					x = 1;
    					break;
    				}
    			}
    		}
    	}
    	return x;
    }
    /* Get String Length function */
    int getlength(char str[]) {
    	int len = 0;
    	while(str[len] != '\0') len++; return len;
    }

  7. #7
    Registered User
    Join Date
    Oct 2007
    Posts
    38
    A problem: if i change str2 to "s " (s followed by a space character) I get a NOT FOUND outcome...
    Last edited by Karpaty; 12-19-2007 at 03:41 PM.

  8. #8
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,046
    Code:
    /* Get String Length function */
    int getlength(char str[]) {
    	int len = 0;
    	while(str[len] != '\0') len++; return len;
    }
    That indentation is just confusing.

    Consider using strncmp() in your strstr(), as Salem has already said.

    If you want a really short solution, consider recursion. It's really inefficient and everything, but you can basically code strstr like this:
    Code:
    const char *recursive_strstr(const char *in, const char *what) {
        if(!in || !*in) return 0;
        if(strncmp(in, what, strlen(what)) == 0) return in;
        return recursive_strstr(in + 1, what);
    }
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  9. #9
    Registered User
    Join Date
    Oct 2007
    Posts
    38
    Well, we've been told that for the exams we wont be allowed to use any library fuctions apart from those in stdio.h

  10. #10
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,046
    Well, that's absolutely stupid.

    Be that as it may, as Salem has already mentioned, there's no harm in using the built-in strlen() or strncmp() or whatever for your strstr() as you're writing it. And (I seem to be repeating Salem a lot!) it would be best if you modularized your strstr() so that it called strncmp() for example, rather than doing everything itself in an unreadable mess.

    Or you could develop it in a bottom-up approach, writing your own strncmp() before tackling strstr().
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  11. #11
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,485
    Start like this
    Code:
    int myStrncmp ( const char *a, const char *b, size_t len ) {
        return strncmp( a, b, len );
    }
    
    size_t myStrlen ( const char *a ) {
        return strlen( a );
    }
    
    char *myStrstr ( const char *haystack, const char *needle ) {
        return strstr( haystack, needle );
    }
    Then refine one of the functions to say
    Code:
    char *myStrstr ( const char *haystack, const char *needle ) {
        size_t h_len = myStrlen( haystack );
        size_t n_len = myStrlen( needle );
        size_t i;
        for ( i = 0 ; i < (h_len-n_len) ; i++ ) {
            if ( myStrncmp( &haystack[i], needle, n_len ) == 0 ) {
                return &haystack[i];
            }
        }
        return NULL;
    }
    The point is, you start with something which works, which means when you write your own version and it stops working, you have some idea of where the problem is.

    > Well, we've been told that for the exams we wont be allowed to use any library fuctions
    That's only in the answer you hand in. Nothing wrong with using them to get you moving forwards.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  12. #12
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,538
    Quote Originally Posted by Karpaty View Post
    Code:
    	if(result == 1) printf("Not Found");
        else printf("Found");
    This one's misaligned! Try indenting it to match the if.
    And don't mix spaces and tabs - use one! It will mess up the indentation outside your editor. I recommend only tabs.
    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
    Registered User
    Join Date
    Jun 2007
    Posts
    63

    my_strstr

    Without the use of any function of string.h which i agree of being a stupid thing to do here is my code for strstr.

    Code:
    //---------------------------------------------------------------------------
    
    #include <stdio.h>
    
    int my_strlen(const char *str)
    {
    	int i;
    	for(i = 0; str[i] != '\0'; i++);
    	return i;
    }
    
    char *my_strstr(char *source, char *str)
    {
    
    	int i,u, j = 0;
    	/* Return Value. */
    	char *ptrToStr = NULL;
    	/* Get the lengths. */
    	int nLen = my_strlen(source);
    	int sLen = my_strlen(str);
    	if(!source)
    		return NULL;
    	if(sLen > nLen)
    		return NULL;
    	for(i = 0; i < nLen; i++)
    	{
    		if(source[i] == str[j])
    		{
    			u = i;
    			for(j = 0; j < sLen && str[j] == source[u]; j++, u++);
    			if(j == sLen)
    			{
    				/* Save a pointer to the start position. */
    				ptrToStr = &source[i];
    				return ptrToStr;
    			}
    		}
    	}
    	/* Return NULL. */
    	return NULL;
    }
    
    //---------------------------------------------------------------------------
    
    int main(int argc, char* argv[])
    {
    	char *mainstr = "This is a nice day.";
    	char *substr = "This";
    	char *strptr = my_strstr(mainstr, substr);
    	printf("&#37;s\n", strptr);
    	printf("Hit enter to quit.....\n");
    	getchar();
    	return 0;
    }
    //---------------------------------------------------------------------------
    Last edited by Bokarinho; 12-21-2007 at 04:53 PM. Reason: Elysia

  14. #14
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,538
    Intuition tells me you could probably just return i from my_strlen since both strLen and i are incremented on each loop (though you might have to do strLen - 1).
    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.

  15. #15
    Registered User
    Join Date
    Jun 2007
    Posts
    63
    Indeed.

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C++ ini file reader problems
    By guitarist809 in forum C++ Programming
    Replies: 7
    Last Post: 09-04-2008, 06:02 AM
  2. Compile Error that i dont understand
    By bobthebullet990 in forum C++ Programming
    Replies: 5
    Last Post: 05-05-2006, 09:19 AM
  3. Replies: 4
    Last Post: 03-03-2006, 01:11 AM
  4. Linked List Help
    By CJ7Mudrover in forum C Programming
    Replies: 9
    Last Post: 03-10-2004, 09:33 PM
  5. string manipulation
    By SPEKTRUM in forum Linux Programming
    Replies: 3
    Last Post: 01-26-2002, 10:41 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21