如何在c中剪切字符串的一部分? [英] How to cut part of a string in c?

查看:608
本文介绍了如何在c中剪切字符串的一部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找出如何在C语言中剪切字符串的一部分。例如,您有一个字符串狗死了,因为汽车在横过马路时撞了他,该函数将如何使句子有汽车撞过马路或有汽车撞他

I'm trying to figure out how to cut part of a string in C. For example you have this character string "The dog died because a car hit him while it was crossing the road" how would a function go making the sentence "a car hit him while crossing the road" or "a car hit him"

如何使用C的库(或/和自定义函数) ?

How do you go about this with C's library (or/and) a custom function?

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

ok I don't have the main code but this is going to be the structure of this experiment

#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;
}


推荐答案

以下函数将给定超出char缓冲区的范围。该范围由起始索引和长度标识。可以指定一个负长度,以指示从字符串的起始索引到结尾的范围。

The following function cuts a given range out of a char buffer. The range is identified by startng index and length. A negative length may be specified to indicate the range from the starting index to the end of the string.

/*
 *      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;
}

通过移动范围内的所有内容(包括终止的'\0'到具有 memmove 的起始索引,从而覆盖范围。范围内的文本会丢失。

The char range is cut out by moving everything after the range including the terminating '\0' to the starting index with memmove, thereby overwriting the range. The text in the range is lost.

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

Note that you need to pass a char buffer whose contents can be changed. Don't pass string literals that are stored in read-only memory.

这篇关于如何在c中剪切字符串的一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆