Thread: How do I write this function?

  1. #1
    Asian Pride
    Join Date
    Apr 2004
    Posts
    6

    How do I write this function?

    Here is the problem that I have read it several times but still don't know whether I must return the memory address (is a number) or the character of the string (a character).

    Write a function find with two parameters: str and substr. The parameters str and substr are pointers to char. {*the following sentence is what I dont understand*} The function find returns the address of the first occurrence of the string pointed by substr in the string pointed to by str. If the string pointed to by substr does not occur in the string pointed to by str, find returns NULL.

    This is like a strchr() function already written for the compiler. But how can we write our own?
    Last edited by Cyb3rT3k; 04-25-2004 at 08:36 PM.

  2. #2
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    look up strchr() and strstr()

    Ah hell I'll be nice:
    NAME
    strchr, strrchr - locate character in string

    SYNOPSIS
    #include <string.h>

    char *strchr(const char *s, int c);

    char *strrchr(const char *s, int c);

    DESCRIPTION
    The strchr() function returns a pointer to the first occurrence of the character c in the string s.

    The strrchr() function returns a pointer to the last occurrence of the character c in the string s.

    RETURN VALUE
    The strchr() and strrchr() functions return a pointer to the matched character or NULL if the character is not found.

    CONFORMING TO
    SVID 3, POSIX, BSD 4.3, ISO 9899

    SEE ALSO
    index(3), memchr(3), rindex(3), strpbrk(3), strsep(3), strspn(3), strstr(3), strtok(3)
    NAME
    strstr - locate a substring

    SYNOPSIS
    #include <string.h>

    char *strstr(const char *haystack, const char *needle);

    DESCRIPTION
    The strstr() function finds the first occurrence of the substring needle in the string haystack. The terminating `\0' characters are
    not compared.

    RETURN VALUE
    The strstr() function returns a pointer to the beginning of the substring, or NULL if the substring is not found.

    BUGS
    Early versions of Linux libc (like 4.5.26) would not allow an empty argument. Later versions (like 4.6.27) work correctly, and return
    haystack when needle is empty.

    SEE ALSO
    index(3), memchr(3), rindex(3), strchr(3), strpbrk(3), strsep(3), strspn(3), strtok(3)
    Play with these two functions to see how your functions should work.

  3. #3
    Asian Pride
    Join Date
    Apr 2004
    Posts
    6
    umm ... thanks man ... but then these functions are already written for the compiler. Yeah, we can use it. But the problem is I have to write my own function. I appreciate it anyway

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    Well have you got as far as
    Code:
    char *foo ( char *str ) {
      char *p;
      for ( p = str ; *p != '\0' ; p++ ) {
        printf( "%c\n", *p );
      }
      return str;
    }
    That's your basic string scanning loop - now add an if() or two as appropriate
    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.

  5. #5

    Post

    Hello,

    Here are replica's of the functions strstr() and strchr(), rename them to whatever you want, etc...

    Code:
    #include <stdlib.h> // for printf()
    
    char* strchr(const char *, int);
    char* strstr(const char *, const char *);
    
    int main() {
    	int spaces=0;
    	char *pch;
    	char data[255] = {"This is a string"};
    
    	/*
    	** Search for first ' '
    	** and all there after
    	*/
    	pch = strchr(data, ' ');
    	while (pch != NULL) {			// while found, and not the end...
    		spaces++;
    		pch = strchr(pch+1, ' ');	// search again
    	}
    	printf("%i spaces found in sentence\n", spaces);
    
    	/*
    	** Search for "is"
    	*/
    	pch = strstr(data, "is");
    	while (pch != NULL) {			// while found, and not the end...
    		printf("is was found at position %i\n", pch-data);
    		pch = strstr(pch+1, "is");	// search again
    	}
    
    	return 0;
    }
    
    char* strchr(const char *string, int c) {
    	while( *string ) {
    		if( *string == c )
    			return (char *)string;
    		string++;
    	}
    
    	return (char *)0;
    }
    
    char* strstr(const char *string1, const char *string2) {
    	int i;
    
    	while( *string1 ) {
    		for( i = 0; string2[i]; i++ ) {
    			if( string1[i] != string2[i] )
    				break;
    		}
    
    		if( !string2[i] )
    			return (char *)string1;
    		string1++;
    	}
    
    	return (char *)0;
    }
    I also wrote an example in main() of how they are used. They respond exactly like the ones in the string library, so there shouldn't be to much of a difference. If you have any further questions, feel free to ask.


    I hope this helps,
    - Stack Overflow
    Last edited by Stack Overflow; 04-26-2004 at 01:17 PM. Reason: removed static
    Segmentation Fault: I am an error in which a running program attempts to access memory not allocated to it and core dumps with a segmentation violation error. This is often caused by improper usage of pointers, attempts to access a non-existent or read-only physical memory address, re-use of memory if freed within the same scope, de-referencing a null pointer, or (in C) inadvertently using a non-pointer variable as a pointer.

  6. #6
    Registered User linuxdude's Avatar
    Join Date
    Mar 2003
    Location
    Louisiana
    Posts
    926
    Why do you have i declared as static. It isn't needed

  7. #7
    Well,

    Because for some compilers it compiles the code from the top to the bottom, so if I dont have the static definitions, my compiler gives errors saying it doesn't know what that function is. I could just move the strstr() and strchr() examples above main() removing the static definitions.

    I just wanted to give a complete example in case anyone likes their function(s) underneath the main() call and come back to me saying 'strstr() is undeclared', etc...

    Edit: Besides, I've been reading the book "The C Programming Language" by K & R, and most of there examples always have the codes underneath main() and static defintions above main(). That's how C works, C++ may be different.


    - Stack Overflow
    Last edited by Stack Overflow; 04-26-2004 at 12:11 PM.
    Segmentation Fault: I am an error in which a running program attempts to access memory not allocated to it and core dumps with a segmentation violation error. This is often caused by improper usage of pointers, attempts to access a non-existent or read-only physical memory address, re-use of memory if freed within the same scope, de-referencing a null pointer, or (in C) inadvertently using a non-pointer variable as a pointer.

  8. #8
    Registered User linuxdude's Avatar
    Join Date
    Mar 2003
    Location
    Louisiana
    Posts
    926
    I was just wondering thought myinterpretation of static was wrong

  9. #9
    I'm not sure what its actually called. The best name I can think of is the function prototype declaration.

    I guess its supposed to help some by saying char* strstr(const char *, const char *); is a function that expects two char * arguments and returns a char *. That declaration, psuedo function prototype, has to complywith the defintion and uses of strstr().


    - Stack Overflow
    Last edited by Stack Overflow; 04-26-2004 at 12:19 PM.
    Segmentation Fault: I am an error in which a running program attempts to access memory not allocated to it and core dumps with a segmentation violation error. This is often caused by improper usage of pointers, attempts to access a non-existent or read-only physical memory address, re-use of memory if freed within the same scope, de-referencing a null pointer, or (in C) inadvertently using a non-pointer variable as a pointer.

  10. #10
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    You mis-used static for function prototype

    What linuxdude was asking (as am I) is why
    Code:
    char* strstr(const char *string1, const char *string2) {
    	static int i;   // <<<---  this is static
    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.

  11. #11

    Arrow

    Ah,

    Now I understand. Well i'm not sure why that was there, I think I made a mis-type a couple of weeks back when I wrote the function. Thanks again for pointing that out, and I modified my original post.


    - Stack Overflow
    Segmentation Fault: I am an error in which a running program attempts to access memory not allocated to it and core dumps with a segmentation violation error. This is often caused by improper usage of pointers, attempts to access a non-existent or read-only physical memory address, re-use of memory if freed within the same scope, de-referencing a null pointer, or (in C) inadvertently using a non-pointer variable as a pointer.

  12. #12
    Asian Pride
    Join Date
    Apr 2004
    Posts
    6
    thanks guys! But I figured out that this is the same as strstr function. And I tried to write my own version of strstr(). Here are the codes. The compiler didn't give me any error or warning but when I execute it, there is notin on the DOS screen

    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    char *find(char *str, char *substr);
    main()
    {
    	char *str_test = "There is a white cat next to the windows.";
    	char *substr_test1 = "white";
    	char *substr_test2 = "wild";
    
    	printf("find returns %s \n",find(str_test, substr_test1));
    
    	printf("find returns %s \n",find(str_test, substr_test2));
    	return(0);
    }
    
    /*  Write Function */
    
    char *find(char *str, char *substr)
    {
      char *poption;
      char *pconfig;
    
      pconfig = str;
      poption = substr;
    
      while(*pconfig != '\0')
      {
        if(*poption == *pconfig)
        {
    	poption++;
    	pconfig++;
        }
    
        if(*(poption+1) == '\0')
        {
          pconfig -= strlen(substr);
          
    		while(*pconfig != '*' || *(pconfig-1) != '/')
    		{
    			if(*pconfig == '/' && *(pconfig-1) == '*')
    			{
    			 printf("NO COMMENT: ITS CORRECT!");
    				return(pconfig);
    			}
    
    			pconfig--;
    		}
    
          pconfig += strlen(substr);
          poption = substr;
          pconfig++;
        }
    
        if(*poption != *poption)
        {
          poption = substr;
          pconfig++;
        }
      }
    
      return(NULL);
    }

  13. #13
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Code:
    while(*pconfig != '*' || *(pconfig-1) != '/')
    {
    	if(*pconfig == '/' && *(pconfig-1) == '*')
    What on earth are you doing? You're just trying to make a dupe of strstr, right? If so, why are you checking for specific characters in the middle of your search function?

    Code:
    while you're not at the end of the string to search
        while the current letter of the string to search is not the first letter of what to find
            increment pointer using for string to search
        while the current letter of the string to search is the same as the string to find
            increment both pointers
        if you've run out of the string to find
            then it's been found so return something saying as much
    return null
    I've left off error checking, but it should be trivial to make sure you're staying within the bounds of your strings.

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

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Compiling sample DarkGDK Program
    By Phyxashun in forum Game Programming
    Replies: 6
    Last Post: 01-27-2009, 03:07 AM
  2. Including lib in a lib
    By bibiteinfo in forum C++ Programming
    Replies: 0
    Last Post: 02-07-2006, 02:28 PM
  3. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  4. Replies: 5
    Last Post: 02-08-2003, 07:42 PM
  5. Interface Question
    By smog890 in forum C Programming
    Replies: 11
    Last Post: 06-03-2002, 05:06 PM