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

时间:2013-12-03 03:53:19

标签: c string cut

我正在试图弄清楚如何在C中切割一部分字符串。例如,你有这个字符串“狗死了,因为一辆车在过马路时撞到了他”一个功能如何制作句子“一辆车在过马路时撞到了他”或“一辆车撞到了他”

你如何使用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;
}

6 个答案:

答案 0 :(得分:7)

strncpy只能复制n个字符。您可以选择在字符串中移动指针,并且如果您有可写内存,还可以将\0粘贴到数组中以提前终止它。

答案 1 :(得分: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;
}

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

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

答案 2 :(得分:3)

对于这样的问题,最好是编写自己的功能,这需要时间,但它会得到回报。函数 str_slice 的代码如下所示,与JavaScripts的函数 string.slice https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice)和Python&#非常相似39;用于在字符串或数组上创建切片的功能(https://docs.python.org/3.5/library/functions.html#slice)。

它也只基于C标准库,因此必须跨平台并与任何编译器一起使用。如果有疑问,可以查看测试。

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


/**
 * Extracts a selection of string and return a new string or NULL.
 * It supports both negative and positive indexes.
 */
char *
str_slice(char str[], int slice_from, int slice_to)
{
    // if a string is empty, returns nothing
    if (str[0] == '\0')
        return NULL;

    char *buffer;
    size_t str_len, buffer_len;

    // for negative indexes "slice_from" must be less "slice_to"
    if (slice_to < 0 && slice_from < slice_to) {
        str_len = strlen(str);

        // if "slice_to" goes beyond permissible limits
        if (abs(slice_to) > str_len - 1)
            return NULL;

        // if "slice_from" goes beyond permissible limits
        if (abs(slice_from) > str_len)
            slice_from = (-1) * str_len;

        buffer_len = slice_to - slice_from;
        str += (str_len + slice_from);

    // for positive indexes "slice_from" must be more "slice_to"
    } else if (slice_from >= 0 && slice_to > slice_from) {
        str_len = strlen(str);

        // if "slice_from" goes beyond permissible limits
        if (slice_from > str_len - 1)
            return NULL;

        buffer_len = slice_to - slice_from;
        str += slice_from;

    // otherwise, returns NULL
    } else
        return NULL;

    buffer = calloc(buffer_len, sizeof(char));
    strncpy(buffer, str, buffer_len);
    return buffer;
}

<强>测试

#include <assert.h>

void
test_str_slice()
{
    char str[] = "abcdefghijkl";

    assert(NULL == str_slice(str, -3, -10));
    assert(NULL == str_slice(str, -1, -2));
    assert(NULL == str_slice(str, -1, 0));
    assert(NULL == str_slice(str, 1, 0));
    assert(NULL == str_slice(str, 5, 4));
    assert(NULL == str_slice(str, 0, 0));
    assert(NULL == str_slice(str, 10, 10));
    assert(NULL == str_slice(str, -2, -2));
    assert(NULL == str_slice(str, -20, -12));
    assert(NULL == str_slice(str, -20, -13));
    assert(NULL == str_slice(str, 12, 13));
    assert(NULL == str_slice(str, 12, 20));
    assert(NULL == str_slice("", 1, 2));
    assert(NULL == str_slice("", -2, -1));
    assert(strcmp(str_slice(str, -3, -1), "jk") == 0);
    assert(strcmp(str_slice(str, -8, -3), "efghi") == 0);
    assert(strcmp(str_slice(str, -10, -9), "c") == 0);
    assert(strcmp(str_slice(str, -2, -1), "k") == 0);
    assert(strcmp(str_slice(str, -15, -1), "abcdefghijk") == 0);
    assert(strcmp(str_slice(str, -12, -2), "abcdefghij") == 0);
    assert(strcmp(str_slice(str, -15, -8), "abcd") == 0);
    assert(strcmp(str_slice(str, -15, -11), "a") == 0);
    assert(strcmp(str_slice(str, 1, 3), "bc") == 0);
    assert(strcmp(str_slice(str, 11, 100), "l") == 0);
    assert(strcmp(str_slice(str, 2, 4), "cd") == 0);
    assert(strcmp(str_slice(str, 3, 6), "def") == 0);
    assert(strcmp(str_slice(str, 0, 1), "a") == 0);
    assert(strcmp(str_slice(str, 4, 6), "ef") == 0);
    assert(strcmp(str_slice(str, 1, 2), "b") == 0);
    assert(strcmp(str_slice(str, 0, 3), "abc") == 0);
    assert(strcmp(str_slice(str, 0, 11), "abcdefghijk") == 0);
    assert(strcmp(str_slice(str, 2, 10), "cdefghij") == 0);
    assert(strcmp(str_slice(str, 0, 50), "abcdefghijkl") == 0);
}

正如您在测试中看到的,函数返回一个字符串或NULL。它还支持消极和正面指数。这个想法来自JavaScript和Python提到的早期功能。所以,不要污染这个答案大量的文字,我建议你阅读JavaScript和Python的文档。

答案 3 :(得分:2)

如果你知道字符串的内容,

strstr对你来说是完美的。

示例:

char *str = "A dog died because a car hit him while he was crossing the road.";
char *pCh = strstr(str, "dog");

pCh'd'中包含"dog"的地址。

答案 4 :(得分:0)

http://www.cplusplus.com/reference/cstring/

您可以使用strstr(获取子字符串),strtok(使用某些标记拆分)等函数,

答案 5 :(得分:0)

您可以通过简单的代码使用类似于Python的[n:m] cut运算符的方法,但是它涉及动态分配,还保留了作为输入的原始字符串。

char* cutoff(const char* str, int from , int to)
{
    if (from >= to)
        return  NULL;

    char* cut = calloc(sizeof(char), (to - from) + 1);
    char* begin = cut;
    if (!cut)
        return  NULL;

    const char* fromit = str+from;
    const char* toit = str+to;
    (void)toit;
    memcpy(cut, fromit, to);
    return begin;
}