首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C >> 關於C

C 語言字符串編輯技術:插入與刪除函數完整實現

     編輯:關於C

功能概述

實現兩個基礎字符串操作函數:

  • cinsert(char c, char *str, int pos):在字符串 str 的第 pos 位置插入字符 c。
  • cdelete(char *str, int pos):刪除字符串 str 中第 pos 個字符。

均針對以 \0 結尾的 C 風格字符串,原地修改,無需返回值。

核心邏輯解析

插入函數 cinsert

  1. 獲取字符串長度 len。
  2. 邊界修正:pos < 0 → 0,pos ≥ len → len(尾部追加)。
  3. 從末尾向前搬移字符:for (i = len; i >= pos; i--) str[i+1] = str[i],騰出空位。
  4. 在 str[pos] 寫入新字符。

刪除函數 cdelete

  1. 檢查合法性:字符串非空、0 ≤ pos < len。
  2. 前移覆蓋: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
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved