溫馨提示×

c語言中怎么用string函數提取字符串

小億
215
2023-11-17 12:44:09
欄目: 編程語言

在C語言中,可以使用string.h頭文件中的一些函數來提取字符串。

  1. 使用strncpy函數:
#include <stdio.h>
#include <string.h>

int main() {
    char source[] = "Hello, World!";
    char destination[20];
    int n = 5; // 提取的字符數

    strncpy(destination, source, n);
    destination[n] = '\0';

    printf("提取的字符串為:%s\n", destination);

    return 0;
}
  1. 使用sscanf函數:
#include <stdio.h>

int main() {
    char source[] = "Hello, World!";
    char destination[20];

    sscanf(source, "%20s", destination);

    printf("提取的字符串為:%s\n", destination);

    return 0;
}
  1. 使用strtok函數:
#include <stdio.h>
#include <string.h>

int main() {
    char source[] = "Hello, World!";
    char *token;

    token = strtok(source, " "); // 以空格為分隔符

    while (token != NULL) {
        printf("提取的字符串為:%s\n", token);
        token = strtok(NULL, " "); // 繼續提取下一個字符串
    }

    return 0;
}

以上是幾種常見的提取字符串的方法,具體使用哪種方法取決于所需的功能和要求。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女