Thread: how to break a string into array of strings

  1. #1
    Banned
    Join Date
    Oct 2008
    Posts
    1,535

    how to break a string into array of strings

    i have a string in which words are separated by space

    i want to create an array of strings ,each string contains a word
    from the original string

    i tried like this.
    but the debugger doesnt show me the stucture
    i just says bad ptr

    i cant see why its not breaking into peaces
    ??
    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    typedef struct node node;
    struct node{
    	int value;
    	struct node * next;
    };
     int countletters(char *str);
     char * sortbycount(char* str);
    void main()
    {
    	int g;
    	char  str[18]="aabx bXcb bBxaDAa";
    	char * r;
    	g=countletters(str);
    	r=sortbycount(str);
    }
    
    
    int countletters(char *str)
    {
    	int i,cnt=0;
    	int ch[26]={0};
        for (i=0;i<(int)strlen(str);i++)
    	{
           if ((str[i]>='a')&&(str[i]<='z'))
    	   {
              ch[str[i]-'a']=1;
    	   }
    	   if ((str[i]>='A')&&(str[i]<='Z'))
    	   {
              ch[str[i]-'A']=1;
    	   }
    	}
    	for (i=0;i<26;i++)
    	{
    		if(ch[i]==1){ cnt++;}
    	}
    	printf("%d",cnt);
       return cnt;
    }
    
    char * sortbycount(char* str)
    {
      int start=0,i,cnt=0;char** arr;
      for (i=0;i<(int)strlen(str);i++)
      {
        if (str[i]==' ') cnt++;
      }
      arr=(char**)malloc(sizeof(char*)*cnt);
      i=0;
      do
      {
         for (i=start;str[i]!=' ';i++);
         arr[i]=(char*)malloc(sizeof(char)*(i-start));
         sprintf(arr[i],"%s",str+i); 
    	 start=i;
    
      }while(i<cnt);
      
     return str;
    }

  2. #2
    Registered User
    Join Date
    Sep 2001
    Posts
    4,912
    Is there a reason you're not using strtok? It would make this a whole lot easier - you just pass it a string and a delimiter (' ', in this case), and each subsequent call will return a pointer to the next word...

    I suspect you wrote this program all at once and then tried compiling it - have you tried writing the program in small pieces and testing it at each stage? It's a lot easier to debug one small function than a whole program. Also, if you post an error, tell us what line the error occurs on.

  3. #3
    DESTINY BEN10's Avatar
    Join Date
    Jul 2008
    Location
    in front of my computer
    Posts
    804
    Quote Originally Posted by transgalactic2 View Post
    i have a string in which words are separated by space

    i want to create an array of strings ,each string contains a word
    from the original string

    i tried like this.
    but the debugger doesnt show me the stucture
    i just says bad ptr

    i cant see why its not breaking into peaces
    ??
    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    typedef struct node node;
    struct node{
    	int value;
    	struct node * next;
    };
     int countletters(char *str);
     char * sortbycount(char* str);
    void main()
    {
    	int g;
    	char  str[18]="aabx bXcb bBxaDAa";
    	char * r;
    	g=countletters(str);
    	r=sortbycount(str);
    }
    
    
    int countletters(char *str)
    {
    	int i,cnt=0;
    	int ch[26]={0};
        for (i=0;i<(int)strlen(str);i++)
    	{
           if ((str[i]>='a')&&(str[i]<='z'))
    	   {
              ch[str[i]-'a']=1;
    	   }
    	   if ((str[i]>='A')&&(str[i]<='Z'))
    	   {
              ch[str[i]-'A']=1;
    	   }
    	}
    	for (i=0;i<26;i++)
    	{
    		if(ch[i]==1){ cnt++;}
    	}
    	printf("%d",cnt);
       return cnt;
    }
    
    char * sortbycount(char* str)
    {
      int start=0,i,cnt=0;char** arr;
      for (i=0;i<(int)strlen(str);i++)
      {
        if (str[i]==' ') cnt++;
      }
      arr=(char**)malloc(sizeof(char*)*cnt);
      i=0;
      do
      {
         for (i=start;str[i]!=' ';i++);
         arr[i]=(char*)malloc(sizeof(char)*(i-start));
         sprintf(arr[i],"%s",str+i); 
    	 start=i;
    
      }while(i<cnt);
      
     return str;
    }
    Over a 1000 posts and still you're using it.
    HOPE YOU UNDERSTAND.......

    By associating with wise people you will become wise yourself
    It's fine to celebrate success but it is more important to heed the lessons of failure
    We've got to put a lot of money into changing behavior


    PC specifications- 512MB RAM, Windows XP sp3, 2.79 GHz pentium D.
    IDE- Microsoft Visual Studio 2008 Express Edition

  4. #4
    uh oh
    Join Date
    Jan 2005
    Location
    Ontario, CA
    Posts
    66
    Also using (int)strlen(str) for the condition of a loop statement is also unwise, it forces the program to do this calculation on each pass of the loop.. increasing the processing resources/time required for the program to finish its job. I would suggest using an int variable holding the value of (int)strlen(str) and then using this value in the condition of the loop. This way that one calculation is only completed once, but still as functional for the overall design with an increase in performance.

    Code:
    int len=(int)strlen(str);
    for( i=0 ; i < len ; i++ ) {
        // do some processing here
    }
    I'm not sure though, but what is the purpose of counting the letters? It seems to serve no purpose other then to output the total number of separate (not including repeats) characters found within the string. This doesn't seem to have a purpose in terms of separating a string into various smaller array blocks, but I do agree that strtok would do this program a lot of justice.

  5. #5
    Banned
    Join Date
    Oct 2008
    Posts
    1,535
    i am not alowed to use strtok

  6. #6
    Banned
    Join Date
    Oct 2008
    Posts
    1,535
    i am counting the spaces and the number of words is the number of spaces+1

  7. #7
    Registered User
    Join Date
    Jun 2009
    Posts
    486
    use getc to read in one character at a time
    while the character is not a space
    append the character to the current array index
    when you hit a space
    increment the index
    repeat

  8. #8
    Banned
    Join Date
    Oct 2008
    Posts
    1,535
    thats what i did in sprintf
    it should stop copying when it gets a space
    because its %s

  9. #9
    Registered User
    Join Date
    Sep 2001
    Posts
    4,912
    thats what i did in sprintf
    it should stop copying when it gets a space
    because its %s
    Have you, by any chance, tested to see if that's what it's doing? %s reads a string, not a word.

  10. #10
    Banned
    Join Date
    Oct 2008
    Posts
    1,535
    i know
    it should stop copying when it gets a space
    because its %s
    but in this fixed
    it copies the whole thing
    ??

    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    typedef struct node node;
    struct node{
    	int value;
    	struct node * next;
    };
     int countletters(char *str);
     char * sortbycount(char* str);
    void main()
    {
    	int g;
    	char  str[18]="aabx bXcb bBxaDAa";
    	char * r;
    	g=countletters(str);
    	r=sortbycount(str);
    }
    
    
    int countletters(char *str)
    {
    	int i,cnt=0;
    	int ch[26]={0};
        for (i=0;i<(int)strlen(str);i++)
    	{
           if ((str[i]>='a')&&(str[i]<='z'))
    	   {
              ch[str[i]-'a']=1;
    	   }
    	   if ((str[i]>='A')&&(str[i]<='Z'))
    	   {
              ch[str[i]-'A']=1;
    	   }
    	}
    	for (i=0;i<26;i++)
    	{
    		if(ch[i]==1){ cnt++;}
    	}
    	printf("%d",cnt);
       return cnt;
    }
    
    char * sortbycount(char* str)
    {
      int start=0,t=0,i,cnt=0;char** arr;
      for (i=0;i<(int)strlen(str);i++)
      {
        if (str[i]==' ') cnt++;
      }
      arr=(char**)malloc(sizeof(char*)*(cnt+1));
      i=0;
      do
      {
         for (i=start;str[i]!=' ';i++);
         arr[t]=(char*)malloc(sizeof(char)*(i-start));
         sprintf(arr[t],"%s",str+start); 
    	 start=i;
       t++;
      }while(t<cnt);
      
     return str;
    }

  11. #11
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    >> void main()

    Again, wrong, wrong, wrong.

    >> char** arr;

    Wouldn't it be a good idea to return it's value? And free( ) it when you're done with it, for that matter?

    >> int countletters(char *str)

    If you really want the number of characters, why not simply loop through the string and increment a counter when you come across one?

    >> if (str[i]==' ') cnt++;

    That doesn't count words, but spaces.

    >> for (i=start;str[i]!=' ';i++);

    Notice the semicolen at the end there?

    >> sprintf(arr[t],"%s",str+start);

    sprintf isn't going to help you here.

    Finally (and you've been told this before), you need to indent your code more consistently.
    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;
    }

  12. #12
    Banned
    Join Date
    Oct 2008
    Posts
    1,535
    >> void main()

    Again, wrong, wrong, wrong.
    ========================
    it compiles so its fine by me.


    >> char** arr;

    Wouldn't it be a good idea to return it's value? And free( ) it when you're done with it, for that matter?
    =======================
    an array of strings is **


    >> if (str[i]==' ') cnt++;

    That doesn't count words, but spaces.
    ===============================
    the number of words is the number of spaces +1


    >> sprintf(arr[t],"%s",str+start);

    sprintf isn't going to help you here.
    ==============================
    this sentence doesnt give any information.
    i explained why it should work in previos threads
    you said "isnt going to help"
    very helpfull

  13. #13
    Registered User
    Join Date
    Sep 2001
    Posts
    4,912
    this sentence doesnt give any information.
    I have never, not once, seen you ask a question, AND provide the appropriate information along with that question. You never tell us what you've tried, you never give us detailed errors, etc...

    Furthermore, I already told you very clearly why your sprintf statement isn't going to work. You keep saying "it should" do this, but I just looked in the documentation, and "it should" read a string, not a word. Strings end with null characters, not with spaces. Why on earth should someone else give you more information, if you have 1500 posts proving that you don't learn from what other people have told you?

    it compiles so its fine by me.
    Your problem is that you don't want to learn. The reason you have been posting so long and still can't compile a simple program, is because you don't listen to what anyone tells you. You've never changed the way you ask questions, you've never thought through a problem yourself.

    If you want people to help you - use int main(), because if you use void main(), odds are that they're going to have to edit your program before it will compile for them. Do yourself a favor and use int main().

    i explained why it should work in previos threads
    That's our whole point. You "THINK" things should work, but in reality, they don't. Stop making so many assumptions, and try things. Write a small part of the program, test it. Does it REALLY do what you think it's doing? If so, move on. If not, try and debug that small part of the program.


    I don't mean to sound rude, so please don't take this as a flaming - but everyone on this board is here to help other people, and clearly, you have not been helped by the hundreds of other posts. Please start listening to the advice people give you, otherwise you are never going to learn anything meaningful.

  14. #14
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    >> it compiles so its fine by me.

    Just because your broken compiler accepts it doesn't make it correct (a standard compliant compiler won't compile it).

    >> an array of strings is **

    I was pointing out the fact that you never returned the array, and never freed it.

    >> the number of words is the number of spaces +1

    " How many words is this? "

    According to your algorithm, 7. The point is, you should be counting the number of blocks of consecutive characters, not spaces.

    >> this sentence doesnt give any information.

    Sure it does. Print the value of arr[t] at that point and you'll realize that sprintf is useless in this situation.
    Last edited by Sebastiani; 06-25-2009 at 12:57 PM. Reason: revised count (board edited out extra spaces)
    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;
    }

  15. #15
    Banned
    Join Date
    Oct 2008
    Posts
    1,535
    ok so how to do so it will copy into arr[t] till str reaches a space
    ?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Another syntax error
    By caldeira in forum C Programming
    Replies: 31
    Last Post: 09-05-2008, 01:01 AM
  2. Inheritance Hierarchy for a Package class
    By twickre in forum C++ Programming
    Replies: 7
    Last Post: 12-08-2007, 04:13 PM
  3. ascii rpg help
    By aaron11193 in forum C Programming
    Replies: 18
    Last Post: 10-29-2006, 01:45 AM
  4. Something is wrong with this menu...
    By DarkViper in forum Windows Programming
    Replies: 2
    Last Post: 12-14-2002, 11:06 PM
  5. error with code
    By duffy in forum C Programming
    Replies: 8
    Last Post: 10-22-2002, 09:45 PM