【Linux c】字符串的截取

对字符串的截取:

#include 
#include 

//截断有特殊符号的字符串,并取后段
void cutString_A(char* string) {
    char *p_start = string;
    char newString[32];

    while(*p_start) {
        if (*p_start == '.') {
            p_start++;
            strncpy(newString, p_start, sizeof(newString));
            break;
        }
        p_start++;
    }

    printf("newString = %s\n", newString);
}

//截断有特殊符号的字符串,并取前段
void cutString_B(char* string) {
    char *p_start = string;
    char newString[32];
    int num = 0;

    while(*p_start) {
        if (*p_start == '.') 
            break;
        p_start++;
        num ++;
    }

    strncpy(newString, string, num);
    printf("newString = %s\n", newString);
}

//截取字符串的前n个字符
void cutString_C(char* string, int num) {
    char *p_start = string;
    char newString[32];

    strncpy(newString, p_start, num);
    printf("newString = %s\n", newString);
}

//截取字符串的后n个字符
void cutString_D(char* string, int num) {
    char *p_start = string;
    char newString[32];

    int len = strlen(string);
    strncpy(newString, p_start + (len - num), sizeof(newString));
    
    printf("newString = %s\n", newString);
}


int main(void)
{
    char string[32] = "hello.txt";
    cutString_A(string);
    cutString_B(string);
    cutString_C(string, 5);
    cutString_D(string, 5);

    return 0;
}

 

你可能感兴趣的:(c)