怎么把一个不定长的string字符串嵌入到另一个字符串中
如何把一个不定长的string字符串嵌入到另一个字符串中
eg:this %1% a good idea
用is或者is not这样不固定的string来代替%1%组成一个字符串。有大致思路就ok了。如果有代码就更好了。 脚本语言也可以
------解决方案--------------------
eg:this %1% a good idea
用is或者is not这样不固定的string来代替%1%组成一个字符串。有大致思路就ok了。如果有代码就更好了。 脚本语言也可以
------解决方案--------------------
- C/C++ code
#include<stdio.h> #include<stdlib.h> #include<string.h> main() { char a[10],b[20],c[5]=" is "; char *p="this %1% a good idea"; sscanf(p,"%s",a); sscanf(p,"%*s%*s %[^'/0']",b); strcat(a,c); strcat(a,b); puts(a); }
------解决方案--------------------
用%s可以简单的实现:
- C/C++ code
#include <stdlib.h> #include <string.h> #include <stdio.h> char* strpl(const char* str, const char* substr) { char* p = (char*)malloc(strlen(str) * sizeof(char)); if(p != NULL) sprintf(p, str, substr); return p; } int main(int argc, char* argv[]) { printf("%s\n", strpl("this %s a good idea", "is")); printf("%s\n", strpl("this %s a good idea", "is not")); return 0; }