如何在c中剪切一部分字符串?

ans*_*ker 8 c string cut

我正在试图弄清楚如何在C中切割一部分字符串.例如,你有这个字符串"狗死了,因为一辆车在过马路时撞到了他"一个函数如何制作句子"a过马路时撞到他的车"还是"一辆车撞到了他"

你如何使用C的库(或/和)自定义函数来解决这个问题?

好吧,我没有主要代码,但这将是这个实验的结构

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <getopt.h>
#include "display_usage.c"/*If the user enters wrong arguments it will tell them how it should be */


void cut( const char *file, int option, int first, int last );


int main(int argc, char *argv[] ) {
FILE *fp;
    char ch;
    fp = fopen("test.txt", "r"); // Open file in Read mode

    while (ch!=EOF) {
        ch = fgetc(fp); // Read a Character

        printf("%c", ch);
    }
    fclose(fp); // Close File after Reading
   return 0;
}

void cut( const char *file, int reverse, int first, int last ) {



    return;
}
Run Code Online (Sandbox Code Playgroud)

woo*_*tar 7

strncpy只会复制到n字符.您可以选择在字符串中移动指针,\0如果您有可写内存,也可以将数据插入数组中以提前终止它.

  • 如果源和目标重叠,则不能使用`strncpy()`. (2认同)

M O*_*ehm 5

以下函数从char缓冲区中删除给定范围.范围由startng索引和长度标识.可以指定负长度以指示从起始索引到字符串结尾的范围.

/*
 *      Remove given section from string. Negative len means remove
 *      everything up to the end.
 */
int str_cut(char *str, int begin, int len)
{
    int l = strlen(str);

    if (len < 0) len = l - begin;
    if (begin + len > l) len = l - begin;
    memmove(str + begin, str + begin + len, l - len + 1);

    return len;
}
Run Code Online (Sandbox Code Playgroud)

通过将包括终止的范围之后的所有内容移动'\0'到起始索引来切除char范围memmove,从而覆盖范围.范围内的文本丢失了.

请注意,您需要传递一个可以更改其内容的char缓冲区.不传递存储在只读内存中的字符串文字.