String parsing

This is a discussion on String parsing within the C Programming forums, part of the General Programming Boards category; I am having some problems parsing a certain string. First let me explain what I'm trying to do. This is ...

  1. #1
    Registered User
    Join Date
    Nov 2003
    Posts
    10

    String parsing

    I am having some problems parsing a certain string. First let me explain what I'm trying to do. This is just a small component of a much larger program.

    The string that I have to parse has this format:

    Code:
    name1 name2 name3 name4 name5
    ..etc

    and i want each of the names to be checked seperately by another function. Hence each name has to be somehow parsed indiviodouly. I am trying to basically seperate and analyze each of those name.

    This is what I have so far...and I'm stuck.

    Code:
    char *names, *buffer, nicks[16], *temp;
    
    buffer = strtok(names, " ");			
    			strcat(nicks, buffer);
    			sprintf(temp, "%s ", nicks);
    			do
    			{				
    				buffer = strtok(names, temp);
    				strcat(nicks, buffer);
    				sprintf(temp, "%s ", nicks);
    				printf("%s\n", temp);
                                                                      //launch function to process that name
    //unimportant in this context
    				
    			}while(buffer != NULL);

  2. #2
    Yes, my avatar is stolen anonytmouse's Avatar
    Join Date
    Dec 2002
    Posts
    2,544
    The first time you call strtok, the string is passed as the first argument. Subsequent calls must pass NULL as the first argument.

    Code:
    char names[] = "This is a test"; /* String MUST be modifiable */
    
    /* First call initializes strtok with our string and returns the first token in the string */
    buffer = strtok(names, " ");
    
    while (buffer != NULL)
    {
        printf("%s", buffer);
        /* Now we pass NULL to strtok to get the next token in the string */
        buffer = strtok(NULL, " "); 
    }

  3. #3
    Registered User
    Join Date
    Nov 2003
    Posts
    10
    thanks however, that still doesn't parse my string. I think the issue might be with the algorithm I'm trying to use. Basically the end result is to seperate each of the names and then look at them individouly. I'll continue playing around with strtok but if anybody has an idea about how to parse this let me know.

  4. #4
    C Programmer Stack Overflow's Avatar
    Join Date
    Apr 2004
    Posts
    477

    Post

    Hi CBuild,

    I have written code similar to this before. It may not be the best, but it may help and contribute to what you are looking for. I will simply write a function called parseString(char *, char[][], char); which simply takes the source string, finds your designated char or in this case, a space, and then it seperates them putting them into their own 2-Dimensional char[][].

    Code:
    #include <string.h>
    #include <stdio.h>
    
    int parseString(char *src, char dest[][64], char find);
    
    int main () {
    	int i, total;			// Loop (i), Total found (total)
    	char names[256];		// Dummy variable
    	char seperatedNames[16][64];	// 16 strings, with 64 bytes each
    
    	// String copy data
    	strcpy(names, "name1 name2 name3 name4 name5");
    
    	// Parse the string, and how many ' ' found
    	total = parseString(names, seperatedNames, ' ');
    
    	// Display
    	printf("With %i found and seperated\n\n", total);
    	for (i = 0; i < total; i++) {
    		printf("%s\n", seperatedNames[i]);
    	}
    
    	return 0;
    }
    
    int parseString(char *src, char dest[][64], char find) {
    	int b, l, j, z = 1;			// For loops
    	int location[16] = {0};			// Location of string
    	char *pch;				// Character position
    
    	pch = strchr(src, find);		// Find character
    
    	if (pch == NULL)			// Fail safe
    		return (0);
    
    	while (pch != NULL) {
    		location[z] = pch-src+1;	// Record Location
    		pch = strchr(pch+1, find);	// Find again where left off
    		z++;				// Keep location incremented
    	}
    	location[z] = strlen(src);		// Last position
    
    	/*
    	** Write data to new array per 'find' found
    	*/
    	for (l = 0; l < z; l++) {
    		b = 0;				// Start write pos at 0
    
    		/*
    		** Copy designated bytes per array
    		*/
    		for (j = location[l]; j < location[l+1]; j++) {
    			dest[l][b] = src[j];	// Copy bytes to dest
    			b++;			// Increment
    		}
    		dest[l][b] = '\0';
    	}
    
    	return (z);				// How many 'find' found
    }
    Code 1.1: Parsing a string

    Ok, for an explanation of parseString(), I decided to use a 2-D array instead of a char *[] because I didn't see a need to allocate memory for this small task. Now if course this will be handling large strings and unknown size array's I would recommend you to use malloc(), free(), etc...

    I simply take the *src, search for find, and seperate the lines inserting the data into dest[][]. If you have any question, please feel free to ask, I put some comments in there so you knew what each step was about.


    Hope this helps,
    - 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.

  5. #5
    Registered User
    Join Date
    Nov 2003
    Posts
    10
    Thanks for that function. I'm going to have to modify it slightly for my specific problem but this does pretty much what i wanted.

    I'll prolly end up going with the char *[] rather than the char [][] ..since i might have 5 names in that string or 500 names!

  6. #6
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    I'll prolly end up going with the char *[] rather than the char [][] ..since i might have 5 names in that string or 500 names!
    It's the same thing.
    Code:
    void foo1( char bar1[][SIZE] );
    
    void foo2( char *bar2[SIZE] );
    They have the same effect. Just omit the first size index size of the array, which tells basicly says "I don't know how many there are, but each one is SIZE big."

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

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. char Handling, probably typical newbie stuff
    By Neolyth in forum C Programming
    Replies: 16
    Last Post: 06-21-2009, 04:05 AM
  2. String parsing
    By broli86 in forum C Programming
    Replies: 3
    Last Post: 07-03-2008, 05:06 PM
  3. Message class ** Need help befor 12am tonight**
    By TransformedBG in forum C++ Programming
    Replies: 1
    Last Post: 11-29-2006, 10:03 PM
  4. Replies: 4
    Last Post: 03-03-2006, 01:11 AM
  5. creating class, and linking files
    By JCK in forum C++ Programming
    Replies: 12
    Last Post: 12-08-2002, 01:45 PM

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