Tuesday, July 28, 2009

Can you find multiple characters in a string in C programming?

I would like to search for spaces and newline characters and tabs, so I want a function like





string.find(' '||'\n'||'\t', 0) %26lt;~~~~ But this is obviously not correct syntax. What is the correct way to go about doing this?

Can you find multiple characters in a string in C programming?
I do not have access to a C compiler any more so this may have some typos.





The first thing to understand is that C does not really support a string data type. What it does support is an array of char types with a null byte as the last meaningful byte.





For example, declare a char array of 10 bytes and assign "John" as its initial value:





char name[10] = "John";





What will actually be in the char's of the array is as follows:





name[0] will contain 'J'


name[1] will contain 'o'


name[2] will contain 'h'


name[3] will contain 'n'


name[4] will contain '\0'


The \0 is how a null byte is represented. The remaining five bytes will have values that you cannot predict, the will be whatever the byte in memory had in them, they wont be changed or initialized.





Also remember that in C, the name of an array is always a pointer to the first element in the array.





void Find( char *szValue )


{


/* Create a temp pointer and assign it to the start of the array */


char *szTemp = szValue;





while ( szTemp )


{


if ( szTemp == '\t' )


{


/* Do whatever you wanted to do for a tab character */


}


else if ( szTemp == '\r' )


{


/* Do whatever you wanted to do for return character */


}


else if ( szTemp == '\n' )


{


/* Do whatever you wanted to do for a newline character */


}


szTemp++;


}


}





IF you just want to find the first occurrence of a character within a string, you can use the strchr function, link below to explanation and example.





http://www.cplusplus.com/reference/clibr...





Or if you want to find the first occurrence of a string within a string you can use strstr, link below to explanation and example.





http://www.cplusplus.com/reference/clibr...
Reply:perhaps you're looking for regular expressions.


get regex.h for c.


the pattern for your need would be like "\n|\t" .


get a primer for regex http://www.osix.net/modules/article/?id=...


it's delightfullll. :)


No comments:

Post a Comment