假设我们有以下输入字符串:
Event_Shifts
并且想要这个输出数组:
Admin Input
如何将str[1024]="ABCDEFGHIJKL"
中的每3个字符分成一个子字符串数组?
这是我的代码,但是它只打印前3个字符,而没有实际将它们存储在数组中:
{"ABC", "DEF", "GHI", "JKL"}
答案 0 :(得分:0)
只需遍历整个字符串并将每个字符放在适当的位置即可。不要忘记字符串“ ABC”占用四个字节。
当您浏览输入字符串的字符时,它们进入的输出字符串如下所示:
0,0,0,1,1,1,2,2,2,3,3,3
那是i/3
。他们在输出中进入哪个位置的模式如下:
0、1、2、0、1、2、0、1、2、0、1、2
那是i%3
。因此,如果i
是输入字符串中的位置,则输出数组中的位置是[i/3][i%3]
。因此:
#include <stdio.h>
#include <string.h>
#define MAX 512
int main(){
char str[MAX]="ABCDEFGHIJKL";
int count=0, i=0;
char sub[3];
char arr[MAX/3][4]={};
/* Go through the string putting each character in
its proper place */
for (int i = 0; i < strlen(str); ++i)
arr[i/3][i%3] = str[i];
/* Print the strings out */
for (int i = 0; i < (strlen(str) / 3); ++i)
printf("%s\n", arr[i]);
}
ABC
DEF
GHI
JKL
答案 1 :(得分:0)
Three characters can be scanned using %3c
. This does not terminate the array with a zero so none of the string function can be used that expect that zero terminator.
The %n
specifier will return the number of characters processed by the scan.
Printing can be done by restricting the number of characters with the precision field in %.3s
#include <stdio.h>
#include <stdlib.h>
int main( void) {
char str[]="ABCDEFGHIJKL";
int count = 0;
int span = 0;
int used = 0;
char arr[6][3]={};
while ( count < 6 && 1 == sscanf ( str + span, "%3c%n", &arr[count][0], &used)) {
count++;
span += used;//accumulate number of scanned characters
}
while ( count) {
count--;
printf ( "%.3s\n", arr[count]);//print up to three characters
}
return 0;
}