首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

[菜鸟]C++的字符串生成与解析的有关问题

2012-03-17 
[初学者]C++的字符串生成与解析的问题小弟是C++初学者,刚接触C++四五天,遇到了一个问题,请各位指教。需要两

[初学者]C++的字符串生成与解析的问题
小弟是C++初学者,刚接触C++四五天,遇到了一个问题,请各位指教。

需要两个相匹配的函数:
第一个:
函数功能:将输入的int类型的值,以逗号分隔存入char   *中,如下:
char   *   Generator(int   iValue,char   *cResult);

第二个:
函数功能:与第一个函数刚好相反,需要将字符串以逗号分隔符,解析到字符数组,以方便遍历其中的数字。

因C++上的能力极其有限,尝试了多次都能实现。

请各位指教。

[解决办法]
itoa和atoi
[解决办法]
第一个:
函数功能:将输入的int类型的值,以逗号分隔存入char *中,如下:
char * Generator(int iValue,char *cResult);
--------------------------
使用sprintf();
char *Generator(int iValue, char *cResult) {
sprintf(cResult, "%d, ", iValue);
return cResult;
}

第二个:
函数功能:与第一个函数刚好相反,需要将字符串以逗号分隔符,解析到字符数组,以方便遍历其中的数字。
---------------------------------
这个可以使用strtok把以逗号分隔的字符串分成N个不含逗号的子字符串:
#include <string.h>
char *strtok( char *str1, const char *str2 );


功能:函数返回字符串str1中紧接“标记”的部分的指针, 字符串str2是作为标记的分隔符。如果分隔标记没有找到,函数返回NULL。为了将字符串转换成标记,第一次调用str1 指向作为标记的分隔符。之后所以的调用str1 都应为NULL。

例如:

char str[] = "now # is the time for all # good men to come to the # aid of their country ";
char delims[] = "# ";
char *result = NULL;



result = strtok( str, delims );



while( result != NULL ) {
printf( "result is \ "%s\ "\n ", result );
result = strtok( NULL, delims );
}
以上代码的运行结果是:

result is "now "
result is " is the time for all "
result is " good men to come to the "
result is " aid of their country "

得到的子字符串再使用atoi转换成整型数字:
如:
#include <stdlib.h>
int atoi( const char *str );


功能:将字符串str转换成一个整数并返回结果。参数str 以数字开头,当函数从str 中读到非数字字符则结束转换并将结果返回。例如,

i = atoi( "512.035 " );
i 的值为 512.


[解决办法]
1:char * Generator(int iValue,char *cResult);

#include <string.h>
#include <stdio.h>
#include <stdlib.h>

char * Generator(int iValue,char *cResult);

int main()
{
int i=1;
char result[80]={0};

for(i=1; i <20; i++)
{
Generator(i, result);
printf( "Append %d:\t%s\n ", i, result);
}

system( "PAUSE ");
return 0;
}

char * Generator(int iValue,char *cResult)
{
int index = strlen(cResult);
if(index == 0)
sprintf(cResult, "%d ", iValue);
else
sprintf(cResult+index, ",%d ", iValue);

return cResult;
}

热点排行