Another solution that does not rely on any particular feature and is easily capable of detecting errors is as follows. Note that you need to free the line when the extractUsername () function succeeds.
Note that in C, you simply move around in a sequence of characters using pointer arithmetic. There are several standard library functions, but they are much simpler than anything you can extract from a string.
There are other problems to detect errors, for example, the presence of more than one "@", for example. But that should be enough as a starting point.
// Extract "mail:username@example.com" #include <stdio.h> #include <stdlib.h> #include <string.h> const char * MailPrefix = "mail:"; const char AtSign = '@'; char * extractUserName(const char * eMail) { int length = strlen( eMail ); char * posAtSign = strrchr( eMail, AtSign ); int prefixLength = strlen( MailPrefix ); char * toret = (char *) malloc( length + 1 ); if ( toret != NULL && posAtSign != NULL && strncmp( eMail, MailPrefix, prefixLength ) == 0 ) { memset( toret, 0, length +1 ); strncpy( toret, eMail + prefixLength, posAtSign - prefixLength - eMail ); } else { free( toret ); toret = NULL; } return toret; } int main() { const char * test = "mail:baltasarq@gmail.com"; char * userName = extractUserName( test ); if ( userName != NULL ) { printf( "User name: '%s'\n", userName ); free( userName ); } else { fprintf( stderr, "Error: invalid e.mail address\n" ); return EXIT_FAILURE; } return EXIT_SUCCESS; }
Baltasarq
source share