[语法]字符串的插入与删除

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

void erase(char text[], int index)
{
    int len = strlen(text);
    for(int i = index; i<len ; i++)
    {
        text[i] = text[i + 1]; // 后面的字符前移
    }
}


int main()
{
    char str[10] = "hello";
    erase(str, 1);
    
    return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void erase(char text[], char del)
{
    int len = strlen(text); // 原字符串长度

    int count = 0;
    char* copy = (char*) malloc(len + 1);
    for(int i=0; i<len; i++)
    {
        char ch = text[i];
        if(ch != del )
        {
            copy[count] = ch;
            count ++;
        }
    }
    copy[count] = 0; // 添加结束符
    
    strcpy(text, copy); // 拷回原字符串
    free(copy); // 释放内存
}

int main()
{
    char str[] = "China is a great country with a long history";
    erase(str, 'a');
    
    return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void insert(char text[], int index, char ins)
{
    int len = strlen(text);
    for(int i = len; i >index ; i--)
    {
        text[i] = text[i - 1]; // 后面的字符前移
    }
    text[index] = ins;
}


int main()
{
    char str[10] = "hello";
    insert(str, 1, 'X');
    
    return 0;
}

 

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注