function and strings - C

This is a discussion on function and strings - C within the C Programming forums, part of the General Programming Boards category; I need a function.This function has two arguments.Both of them are strings.This function must do this: if str1=asdfgh and str2=alksh ...

  1. #1
    Registered User
    Join Date
    Aug 2007
    Posts
    63

    function and strings - C

    I need a function.This function has two arguments.Both of them are strings.This function must do this:
    if str1=asdfgh
    and str2=alksh
    then the function must print a string with the characters of str1 that not include characters from str2 so str3=(a)(s)dfg(h) but a,s,h are also characters from str2 and we don't print them
    PHP Code:
    str1=asdfgh
    str2
    =alksh
    str3
    =dfg 
    MY THOUGHT:
    Code:
    #include <stdio.h>
    
    void myfunc(char str1[], char str2[]);
    
    int main(void)
    {
      char str1[]="hello";
      char str2[]="hallo";
    
      myfunc(str1[],str2[]);
    
     return 0;
    }
    
    void myfunc(char str1[], char str2[])
    {
    int i;
     for(i=0; str1[i]; i++)
    {
     if(!(str1[i]==str2[i]))
      printf("%s", str1[i]); /*must print only e*/
      }
    
    }
    note: A)the function finally must print reversely the new string (so str3 = gfd and not dfg)but i begin with the simple case and i belive that after i will can do it and reversly
    B)we also can use pointers
    compile error :func.c:10: error: expected expression before ] token

    Any idea? hint? Pease help!

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,401
    This does not make sense:
    Code:
    myfunc(str1[],str2[]);
    Since you want to pass str1 and str2 as arguments, you should write:
    Code:
    myfunc(str1, str2);
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Aug 2007
    Posts
    63
    Quote Originally Posted by laserlight View Post
    This does not make sense:
    Code:
    myfunc(str1[],str2[]);
    Since you want to pass str1 and str2 as arguments, you should write:
    Code:
    myfunc(str1, str2);
    now i have segmetation fault

  4. #4
    ZuK
    ZuK is offline
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    Code:
    printf("%s", str1[i]); /*must print only e*/
    Wrong format "%s" prints a string.
    Kurt

  5. #5
    Registered User
    Join Date
    Aug 2007
    Posts
    63
    Yes worked.Thank you very much(i feel so stupid about %s).Now i will try to write the function with pointers and print the string reversly.Any hint will be helpfull !

  6. #6
    Registered User
    Join Date
    Aug 2007
    Posts
    63
    first try with pointers
    Code:
    #include <stdio.h>
    #include <string.h>
    
    void myfunc(char *str1, char *str2);
    
    int main(void)
    {
      char *str1="hellos";
      char *str2="hallow";
    
      myfunc(str1,str2);
    
     return 0;
    }
    
    void myfunc(char *str1, char *str2)
    {
    char *p;
    p=str1 + strlen(str1)-1;/*p shows on the end of str1*/
    
    while(p>str1){
     if(!(*p==*str2))
      {printf("&#37;c", *p);}
      
    *p--;
    }
    
    }
    when i run the programm it prints me somethiing like that: ????

    edit: changes in while loop and printf
    Last edited by alzar; 09-14-2007 at 01:11 PM.

  7. #7
    ZuK
    ZuK is offline
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    Code:
     while(*p)
    Won't work . There is no '\0' at the beginning of str1.

    Kurt
    edit:
    Code:
    printf("%c", p);
    Wrong format again p is a pointer to char.
    Last edited by ZuK; 09-14-2007 at 12:31 PM.

  8. #8
    Registered User
    Join Date
    Aug 2007
    Posts
    63
    i make some changes in the code look up my post

  9. #9
    ZuK
    ZuK is offline
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    Code:
    while(*p>str1){
    *p is a char, str1 is a pointer to char.
    Kurt

  10. #10
    Registered User
    Join Date
    Jun 2007
    Posts
    63
    I was taking a closer look into the strpbrk function and got the idea of how using it.
    The following program does what i think you want to do, but think of bugs.
    I have a question too.
    Look in my codes comments and tell me if you can give me an answer.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    char *RemoveSameLetters(char *Buffer1, char *Buffer2)
    {
    	if(Buffer1 == NULL || Buffer2 == NULL)
    	{
    		printf("Invalid String Parametres.\n");
    		return NULL;
    	}
    	else
    	{
    		//Variables.
    		int i;
    		int j = 0;
    		int ptrDiff = 0;
    		int LenB1 = (int)strlen(Buffer1);
    		int LenB2 = (int)strlen(Buffer2);
    		//Initialise Lenght.
    		int Length = LenB1 > LenB2 ? LenB1 : LenB2; 
    		char *pszString = NULL;
    		char *pszPtr = NULL;
    		//Copy Buffer1.
    		char *pszBuffer1 = strdup(Buffer1);
    		//Get space at least the biggest.
    		pszString = calloc(Length, sizeof(char));
    		if(pszString == NULL)
    		{
    			printf("Memory Error.\n");
    			return NULL;
    		}
    		else
    		{
    			pszPtr = strpbrk(Buffer1, Buffer2);
    			//If no characters from Buffer2 are found in Buffer1 return Buffer1.
    			if(pszPtr == NULL)
    				return Buffer1;
    			else
    			{
    				do
    				{
    					ptrDiff = Buffer1 - pszPtr;
    					ptrDiff = ptrDiff > 0 ? ptrDiff  : -ptrDiff;
    					//Words only, if whole sentence remove it.
    					if(pszBuffer1[ptrDiff] == ' ')
    						break;
    					pszBuffer1[ptrDiff] = '0'; //----->I tried use here Buffer1[ptrDiff] but it did not work, so a created a clone of it.
    											   //ptrDiff seemed to get the value of 800678 that is out of boards if i used Buffer1.
    				}while((pszPtr = strpbrk(pszPtr+1, Buffer2)) != NULL);
    				if(pszPtr == NULL)
    				{
    					for(i = 0; i < Length; i++)
    					{
    						if(pszBuffer1[i] != '0')
    							pszString[j++] = pszBuffer1[i];
    					}
    					//Terminate the string.
    					pszString[j] = '\0';
    					//Return it.
    					return pszString;
    				}
    				else
    				{
    					printf("Internal Loop Error.\n");
    					free(pszString);
    					free(pszBuffer1);
    					return NULL;
    				}
    			}
    		}
    	}
    }
    
    int main(int argc, char *argv[])
    {
    	char Buf1[256] = "";
    	char Buf2[256] = "";
    	printf("Give me the first string:");
    	fgets(Buf1, sizeof(Buf1), stdin);
    	printf("Give me the second string:");
    	fgets(Buf2, sizeof(Buf2), stdin);
    	printf("Letters that are not in the second string are:%s\n",RemoveSameLetters(Buf1, Buf2));
    	return 0;
    }
    Results in execution.
    Give me the first string:john
    Give me the second string:tom
    Letters that are not in the second string are:jhn
    Press any key to continue . . .

  11. #11
    Registered User
    Join Date
    Aug 2007
    Posts
    63
    Thanks you very much Bokarinho!!!!!(see my post 13).Now i will see your code.It seems that is what i want but give me a little time to see it.
    Althought yesterday i make another try.This time i use malloc ,because the programm must use exactly as memory he need.My thought is : loop through str1 start from the end , check if not in str2 and then append to arr
    So my code:
    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    char *myfunc(char *str1, char *str2);
    
    int main(void)
    {
      char *str1="hellosr";
      char *str2="hallowfr";
      char *arr;
    
      arr=myfunc(str1,str2);
      printf("&#37;s",arr);
     return 0;
    }
    
    char *myfunc(char *str1, char *str2)
    {
    char *arr, *new;
    char *p;
    
    arr=NULL;
    
    p=str1 + strlen(str1)-1;/*p shows on the end of str1*/
    
    while(p>=str1){
     while(*str2){/* for each p we see if is the same with any character of str2*/
      if (*p!=*str2){
       if (arr=NULL){/*if this is the first element*/
        arr=(char *)malloc(sizeof(char));
        strcat(arr,p);}/*we cat the p in the arr*/
       else{
        arr=(char *)realloc(arr, sizeof(char));
        strcat(arr,p);}
       }
      }
    p--;
    }
    return arr;
    
    }
    The problem: when i run it does not print anything

    ps:again thank you Bokarinho
    Last edited by alzar; 09-15-2007 at 03:50 AM.

  12. #12
    Woof, woof! zacs7's Avatar
    Join Date
    Mar 2007
    Location
    Australia
    Posts
    3,459
    * Learn how to indent, seriously it's hard to read.
    * Don't cast malloc/realloc
    * Check the return value of realloc(), it can fail.
    * Free any memory you allocate

    What about:
    Code:
    void printUnique(const char * a, size_t m, const char * b, size_t n)
    {
        size_t i, f;
    
        /* print unique from a that aren't in b */
        for(i = 0; i < m; i++)
        {
            for(f = 0; f < n; f++)
                /* see if a[i] exists in b or something */
        }
    
        /* do the same thing above for b */
        return;
    }
    Don't over complicate things.

  13. #13
    Registered User
    Join Date
    Aug 2007
    Posts
    63
    @zacs:
    i agree with you that the solution must be simple,but i am confused with the loops(for) and pointers

    @Bokarinho:
    THANK YOU AGAIN. The code works as i want.
    If i understand good your question is why you need to copy the buffer1.It don't make sense to me why we must copy the buffer1, so i make this changes to the code

    Code:
    i delete this:
    //Copy Buffer1.
    char *pszBuffer1 = strdup(Buffer1);
    
    and where you use pszbuffer1 i make it buffer1
    example:
    pszBuffer1[ptrDiff] = '0'; became Buffer1[ptrDiff]
    etc.
    finally the code worked with this changes. Maybe the problem is on your compiler or i don't know?
    i use gcc

    Does anyone see my code ? I am trying to do a simpler solution( i understand the code of Bokarinho but i can't make a simpler )
    i belive that my mistake is on
    if(!(*p==*str2)) these pointers are showing to a hole string and not in character that i want
    any idea?

  14. #14
    Registered User
    Join Date
    Jun 2007
    Posts
    63
    Quote Originally Posted by alzar View Post
    @zacs:
    i agree with you that the solution must be simple,but i am confused with the loops(for) and pointers

    @Bokarinho:
    THANK YOU AGAIN. The code works as i want.
    If i understand good your question is why you need to copy the buffer1.It don't make sense to me why we must copy the buffer1, so i make this changes to the code

    Code:
    i delete this:
    //Copy Buffer1.
    char *pszBuffer1 = strdup(Buffer1);
    
    and where you use pszbuffer1 i make it buffer1
    example:
    pszBuffer1[ptrDiff] = '0'; became Buffer1[ptrDiff]
    etc.
    finally the code worked with this changes. Maybe the problem is on your compiler or i don't know?
    i use gcc

    Does anyone see my code ? I am trying to do a simpler solution( i understand the code of Bokarinho but i can't make a simpler )
    i belive that my mistake is on
    if(!(*p==*str2)) these pointers are showing to a hole string and not in character that i want
    any idea?
    It was nothing serious.
    I cant find out why my Visual Studio 2005 IDE give debugger finds and error to assign the value to Buffer1. You say that in your it works. Well ok, its what i did firstly, so keep it up.
    What is nenx to impove my prog is to use realloc as i create a string with characters of the bigger one so if there are less characters space is useless. I can do it to improve more, tell me if you like it or not. Learn to trust the ready functions of .h rather than creating for yourself new.

  15. #15
    Woof, woof! zacs7's Avatar
    Join Date
    Mar 2007
    Location
    Australia
    Posts
    3,459
    Since this is homework (probably) you're not getting the answer, but here is a pretty good start:

    Code:
    #include <stdio.h>
    #include <string.h>
    
    static void printUnique(const char * a, size_t m, const char * b, size_t n);
    
    int main(void)
    {
        char str1[] = "Hello";
        char str2[] = "Hallo";
    
        /* what's in str1 that isn't in str2 ? */
        printUnique(str1, strlen(str1), str2, strlen(str2));
    
        /* what's in str2 that isn't in str1 ? */
        printUnique(str2, strlen(str2), str1, strlen(str1));
    
        return 0;
    }
    
    static void printUnique(const char * a, size_t m, const char * b, size_t n)
    {
        size_t i, f;
        int found = 0;
    
        /* print unique from a that aren't in b */
        for(i = 0; i < m; i++)
        {
            found = 0;
            for(f = 0; f < n; f++)
            {
                if(a[i] == b[f])
                {
                    found = 1;
                    break;            /* no point checking the rest */
                }
             }
            if(found == 0)
                printf("&#37;c is in a but not b...\n", a[i]);
        }
        return;
    }
    
    /* output:
    e is in a but not b...
    */
    If you have to use pointers just use a pointer to point at a[i], ie

    Code:
    char * ptr;
    
    /* ... */
    for(i = 0; i < m; i++)
    {
        ptr = &a[i];
        printf("value is %c...\n", *ptr);
    /* ... */
    Last edited by zacs7; 09-15-2007 at 04:22 AM. Reason: Optimization, Error

Page 1 of 3 123 LastLast
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, 02:24 PM
  2. Message class ** Need help befor 12am tonight**
    By TransformedBG in forum C++ Programming
    Replies: 1
    Last Post: 11-29-2006, 10:03 PM
  3. Programming using strings
    By jlu0418 in forum C++ Programming
    Replies: 5
    Last Post: 11-26-2006, 07:07 PM
  4. Replies: 3
    Last Post: 03-04-2005, 01:46 PM
  5. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of Cprogramming.com
    Replies: 18
    Last Post: 06-18-2002, 01:27 PM

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