C语言中的字符(串)查找/子串截取


=Start=

缘由:

在Linux下C语言的实际编程中,字符串操作是非常常见的,在此整理一下自己常用到的一些例子,方便以后参考。

正文:

参考解答:
1.子串查找&字符查找(strstr/strchr)
void strchr_test() {
    char *string = "qwerty";
    char *e;
    int index;
    e = strchr(string, 'e');
    if (e == NULL) {
        printf("Character '%c' not found in '%s'\n"'e', string);
        return;
    }
    index = (int)(e - string);
    printf("index of char('%c') in '%s' is %d\n"'e', string, index); // 2
    printf("the rest of str('%s') is '%s'\n", string, e);   // 'erty'
    printf("the rest+1 of str('%s') is '%s'\n", string, e+1); // 'rty'
    printf("\n");
}
void strstr_test() {
    char *str = "sdfadabcGGGGGGGGG";
    char *result = strstr(str, "abc");
    int position = result - str;
    printf("substr('%s') of str('%s') index is %d\n""abc", str, position); // 5
    printf("the rest of str('%s') is '%s'\n", str, result); // 'abcGGGGGGGGG'
    printf("the rest of rest of str('%s') is '%s'\n", str, result+position); // 'GGGGGGG'
}
2.文件按行读取&字符串比较&字符查找&按分隔符切分&字符串转换成整数(getline/strncmp/strchr/strsep/strtol)
#define MAX_PID_COUNT 32
int pid_list[MAX_PID_COUNT] = { [ 0 ... MAX_PID_COUNT-1 ] = -1 };
int usr1_reload() {
    FILE *fp;
    fp = fopen("/tmp/pmon.txt""r"); /* pid_s = 1, 2, 3, 999 */
    if (fp == NULL) {
        perror("fopen");
        return -1;
    }
    char *line = NULL, *index = NULL;
    char pid_str[1024] = {0}, *pid_str_p, *token = NULL, delim[] = ", ";
    size_t len = 0;
    ssize_t nread;
    int i = 0, pid;
    while ((nread = getline(&line, &len, fp)) != -1) {
        if (strncmp(line, "pid_s"5) == 0) {
            index = strchr(line, '=');
            if (index) {
              strncpy(pid_str, index+1, nread-6);
              pid_str_p = pid_str;
              token = strsep(&pid_str_p, delim);
              while(token != NULL){
                  if (token[0] != '\0') {
                    pid = (int) strtol(token, NULL, 10);
                    if (pid <= 0 || pid == (int)LONG_MIN || pid == (int)LONG_MAX) {
                    else {
                      if (i < MAX_PID_COUNT) {
                        pid_list[i++] = pid;
                      }
                    }
                  }
                  token = strsep(&pid_str_p, delim);
              }
            }
            
            break;
        }
    }
    if(line)
        free(line);
    fclose(fp);
    return 0;
}

 

参考链接:

Linux的C语言中获取子串的索引
https://stackoverflow.com/questions/7500892/get-index-of-substring

Linux的C语言中获取字符的索引
https://stackoverflow.com/questions/3217629/how-do-i-find-the-index-of-a-character-within-a-string-in-c

=END=

, ,

发表回复

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