How to split a string into characters in C language?
In C language, you can split a string into characters by iterating through each character in a loop.
Here is a sample code demonstrating how to split a string into characters and print them out:
#include <stdio.h>
#include <string.h>
int main() {
char str[100]; // 假设输入的字符串不超过100个字符
printf("请输入一个字符串:");
fgets(str, sizeof(str), stdin); // 从标准输入读取字符串
int len = strlen(str);
printf("拆分后的字符为:\n");
for (int i = 0; i < len; i++) {
printf("%c\n", str[i]);
}
return 0;
}
In the example code above, we first define a character array called ‘str’ to store the input string. We then use the ‘fgets’ function to read the string from standard input and store it in ‘str’.
Next, we use the strlen function to obtain the length of the string and then use a loop to iterate through each character in the string. Within the loop, we format the character using %c and print it using the printf function. Keep in mind that str[i] represents the i-th character in the string str.
By running this code, you can input a string, and the program will split the string into characters and print them one by one.