这是一些工作代码,它给了我输出:
String: <<20120910T090000>>
String: <<2012-0910T090000>>
String: <<2012-09-10T090000>>
String: <<2012-09-10-T090000>>
String: <<2012-09-10-T-090000>>
String: <<2012-09-10-T-0900-00>>
使用memmove()
它是因为可以保证复制的字符串重叠。
#include <assert.h>
#include <string.h>
#include <stdio.h>
static void insert(char *str, size_t len, char c, size_t pos)
{
memmove(&str[pos+1], &str[pos], len - pos + 1);
str[pos] = c;
}
int main(void)
{
char string[25] = "20120910T090000";
// I want to make it something like "2012-09-10-T-0900-00"
char inschr[] = "-----";
int inspos[] = { 4, 7, 10, 12, 17 };
enum { NUMCHR = sizeof(inschr) / sizeof(inschr[0]) };
enum { NUMPOS = sizeof(inspos) / sizeof(inspos[0]) };
assert(NUMCHR == NUMPOS + 1);
size_t length = strlen(string);
printf("String: <<%s>>\n", string);
for (int i = 0; i < NUMPOS; i++)
{
insert(string, length, inschr[i], inspos[i]);
length++;
printf("String: <<%s>>\n", string);
}
return(0);
}
当然,我假设 C99 支持for
循环符号。还要注意,在经典 C 风格中,代码不采用目标字符串的大小,因此不能确保没有缓冲区溢出。添加参数并进行检查并不难;问题区域是如何指示函数失败。您可以对函数使用不同的接口,将任意长度的字符串插入任意位置;这并不难...
String: <<20120910T090000>>
String: <<2012-0910T090000>>
String: <<2012-09-10T090000>>
String: <<2012-09-10-T090000>>
String: <<2012-09-10-T-090000>>
String: <<2012-09-10-T-0900-00>>
#include <assert.h>
#include <string.h>
#include <stdio.h>
static int insert(char *str, size_t max, size_t len, char *ins, size_t pos)
{
assert(str[len] == '\0');
assert(len < max);
size_t inslen = strlen(ins);
if (len + inslen + 1 >= max)
return -1;
memmove(&str[pos+inslen], &str[pos], len - pos + inslen);
memmove(&str[pos], ins, inslen);
return len + inslen;
}
int main(void)
{
char string[25] = "20120910T090000";
// I want to make it something like "2012-09-10-T-0900-00"
char *insstr[] = { "-", "-", "-", "-", "-" };
int inspos[] = { 4, 7, 10, 12, 17 };
enum { NUMSTR = sizeof(insstr) / sizeof(insstr[0]) };
enum { NUMPOS = sizeof(inspos) / sizeof(inspos[0]) };
size_t length = strlen(string);
assert(NUMSTR == NUMPOS);
printf("String: <<%s>>\n", string);
for (int i = 0; i < NUMPOS; i++)
{
int newlen = insert(string, sizeof(string), length, insstr[i], inspos[i]);
if (newlen < 0)
{
printf("Oops! failed to insert [%s] into [%s]\n", insstr[i], string);
break;
}
length = newlen;
printf("String: <<%s>>\n", string);
}
return(0);
}