實現兩個基礎字符串操作函數:
cinsert(char c, char *str, int pos):在字符串 str 的第 pos 位置插入字符 c。cdelete(char *str, int pos):刪除字符串 str 中第 pos 個字符。均針對以 \0 結尾的 C 風格字符串,原地修改,無需返回值。
cinsertlen。pos < 0 → 0,pos ≥ len → len(尾部追加)。for (i = len; i >= pos; i--) str[i+1] = str[i],騰出空位。str[pos] 寫入新字符。cdelete0 ≤ pos < len。while (pos < len) str[pos] = str[pos+1], pos++,包含結束符 \0 一併前移。#include <string.h>
#include <ctype.h>
#include <stdio.h>
void cinsert(char ccode, char *anystring, int spos);
void cdelete(char *anystring, int spos);
int main(void) {
char p[] = "helloworld";
cinsert('Y', p, 6);
printf("往第6個位置插入字符Y: p = %s\n", p);
cdelete(p, 6);
printf("刪除字符串中的第6個字符: p = %s\n", p);
return 0;
}
void cinsert(char ccode, char *anystring, int spos) {
int p = strlen(anystring);
spos = spos < 0 ? 0 : spos;
spos = spos >= p ? p : spos;
for (; p >= spos; p--) anystring[p+1] = anystring[p];
anystring[spos] = ccode;
}
void cdelete(char *anystring, int spos) {
int p = strlen(anystring);
if (p > 0 && spos >= 0 && spos < p) {
while (spos < p) {
anystring[spos] = anystring[spos+1];
spos++;
}
}
}

輸出:
往第6個位置插入字符Y: p = helloYworld 刪除字符串中的第6個字符: p = helloworld