简体   繁体   中英

C - range of characters in a string

是否有一个功能可以在文本字符串中获取一系列字符,或者我需要自己编写一个函数?

something like this might help

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

main(){
  const char* from = "12345678";
  char *to = (char*) malloc(6);
  strncpy(to, from+2, 5);
}

EDIT : source

Nothing standard, but extremely easy to write:

char *char_range(char begin, char end)
{
    size_t len = end - begin + 1;
    char *arr = malloc(len + 1);
    if (arr)
    {
        size_t i;
        for (i = 0; i < len; ++i)
            arr[i] = (char)(begin + i);
        arr[len] = '\0';
    }
    return arr;
}

Because this generates the range based on the ordinal value of characters, technically this is platform specific. That said, since ASCII and Unicode are pretty much the lingua-franca of most modern OS's these days, you can calls such as:

char *lower_case = char_range('a', 'z');
char *numbers = char_range('0', '9');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM