一道字符串题
wsprintf中有三个参数,前两个为buffer和format,现在给出了buffer和format,其中format只含有“%s”这一种格式,问,怎样输出每一个%s所代表的字符串。例如buffer为“abcdab1234", format为"%sab%s34",那么输出的子字符串应为“abcd”,“12”。
[解决办法]
// strstr.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include "memory.h"#include "string.h"int main(int argc, char* argv[]){ char ori[] = "abcdab1234"; char format[] = "%sab%s34"; char *p = format; char tmp[ 4 ][ 10 ]; int count; int len; int i; memset( tmp, 0, sizeof( tmp ) ); count = 0; len = 0; while( *p ) { if( '%' == *p ) { if( p != format ) { count++; } len = 0; tmp[ count ][ len++ ] = '%'; p++; tmp[ count ][ len++ ] = *p; len = 0; count++; } else { tmp[ count ][ len++ ] = *p; } p++; } count++; for( i = 0; i < count; i++ ) { printf( "format part %d is --- %s \r\n", i + 1, tmp[ i ] ); } char *q = ori; for( i = 0; i < count; i++ ) { if( !strcmp( tmp[ i ], "%s" ) ) { char *t = strstr( q + 1, tmp[ i + 1 ] ); char dest[ 0x10 ] = ""; memcpy( dest, q, ( int )( t - q ) ); printf( "the %%s is %s \r\n", dest ); q += strlen( dest ); q += strlen( tmp[ i + 1 ] ); } } return 0;}