/*
* String segmentation: Splits a long string (which may contain spaces) into a two-dimensional character array.
* And Output
*
* Time complexity O (N)
* Note: When operating a two-dimensional string array, use the "array Pointer" operation to facilitate int (* P) [Len].
*
*/
# Include <stdio. h> # include <string. h> # include <stdlib. h> # include <stdbool. h> # define ndebug # include <assert. h> # define str_size 1000 // input string length # define str_len 50 // Maximum length of the split string # define str_cnt 50 // maximum number of split strings int str_split (char * in_str, char (* out_str) [str_len]); bool is_space (char temp); void str_cpy (char * src_begin, char * src_end, char * DST); int main (void) {char in_str [str_size]; char out_str [str_cnt] [str_len]; In T I = 0; int count; char (* Out) [str_len] = out_str; gets (in_str); Count = str_split (in_str, out_str); While (I <count) {printf ("% s \ n", out [I]); I ++;} return 0;} bool is_space (char temp) {If (temp = ''| temp = '\ n' | temp =' \ T' | temp = '\ V') return true; else return false;} // use a pointer array to pass a two-dimensional array to the int str_split (char * in_str, char (* out_str) [str_len]) {char * temp_in_str; int COUNT = 0; Assert (in_str! = NULL & out_str! = NULL); While (in_str! = '\ 0') {While (is_space (* in_str) in_str ++; If (* in_str =' \ 0') break; temp_in_str = in_str; while (* in_str! = '\ 0 ')&&(! Is_space (* in_str) {in_str ++;} str_cpy (temp_in_str, in_str, out_str [count ++]);} return count;} void str_cpy (char * src_begin, char * src_end, char * DST) {assert (src_begin! = NULL) & (src_end! = NULL) & (DST! = NULL); While (src_begin! = Src_end) * DST ++ = * src_begin ++; * DST = '\ 0'; return ;}
Program running result:
[[email protected] code_test]$ gcc -o string_cat string_cat.c/tmp/ccW8eX4y.o: In function `main':string_cat.c:(.text+0x2d): warning: the `gets' function is dangerous and should not be used.[[email protected] code_test]$ ./string_cat dsdd dda grgr hth jjyjyjyjj ththtdsddddagrgrhthjjyjyjyjjththt
String is split into two-dimensional character Arrays: