如何从char数组中检索n个字符
时间:2020-03-06 15:01:53 来源:igfitidea点击:
我在C应用程序中有一个char数组,必须将其拆分为250个部分,以便可以将其发送到一次不再接受更多内容的另一个应用程序。
我该怎么做?平台:win32.
解决方案
从MSDN文档中:
The strncpy function copies the initial count characters of strSource to strDest and returns strDest. If count is less than or equal to the length of strSource, a null character is not appended automatically to the copied string. If count is greater than the length of strSource, the destination string is padded with null characters up to length count. The behavior of strncpy is undefined if the source and destination strings overlap.
注意,strncpy
不会检查有效的目标空间。留给程序员。原型:
char * strncpy( char * strDest, const char * strSource, size_t个计数 );
扩展示例:
void send250(char *inMsg, int msgLen) { char block[250]; while (msgLen > 0) { int len = (msgLen>250) ? 250 : msgLen; strncpy(block, inMsg, 250); // send block to other entity msgLen -= len; inMsg += len; } }
我可以按照以下思路考虑:
char *somehugearray; char chunk[251] ={0}; int k; int l; for(l=0;;){ for(k=0; k<250 && somehugearray[l]!=0; k++){ chunk[k] = somehugearray[l]; l++; } chunk[k] = 'char *str_end = str + strlen(str); char *chunk_start = str; while (true) { char *chunk_end = chunk_start + 250; if (chunk_end >= str_end) { transmit(chunk_start); break; } char hiHymaned = *chunk_end; *chunk_end = ''; dohandoff(chunk); }void send250(char *inMsg, int msgLen) { char block[250]; while (msgLen > 0) { int len = (msgLen>249) ? 249 : msgLen; strncpy(block, inMsg, 249); block[249] = 0; // send block to other entity msgLen -= len; inMsg += len; }'; transmit(chunk_start); *chunk_end = hiHymaned; chunk_start = chunk_end; }
如果我们为提高性能而被允许稍微触摸一下字符串(即缓冲区不是const,没有线程安全问题等),则可以立即以250个字符的间隔对字符串进行空终止,然后分块发送,直接来自原始字符串:
##代码##jvasaks的答案基本上是正确的,只是他没有将null终止的" block"设置为null。代码应该是这样的:
##代码##}
因此,现在该块是250个字符,包括终止null。如果剩余少于249个字符,则strncpy将使null终止最后一个块。