C言語でString関数を使って文字列を抽出するには?
C言語では、文字列を扱うstring.hヘッダーの関数を利用できます。
- 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;
}
- sscanf関数を使用:
#include <stdio.h>
int main() {
char source[] = "Hello, World!";
char destination[20];
sscanf(source, "%20s", destination);
printf("提取的字符串为:%s\n", destination);
return 0;
}
- 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;
}
文字列を抽出する一般的な方法には以上のようなものがあり、具体的な利用方法は求められる機能や要件によって決まります。