char word[30] = "hello||how||are||you||doing||there"
how can i break the string and display the following output ??
hello|
|how|
|are|
|you|
|doing|
|there
char word[30] = "hello||how||are||you||doing||there"
how can i break the string and display the following output ??
hello|
|how|
|are|
|you|
|doing|
|there
Neglecting any invalid input, you could simply traverse the whole string and preint each character 1 by 1. If you encounter a |, print a newline then skip the following character (assuming they always comes in pairs of 2).
Note: Code has not been tested.Code:char* Pointer = word; while(*Pointer != '\0') { if(*Pointer == '|') { printf("\n"); Pointer++; //Skips extra character } else { printf("%c", *Pointer); } Pointer++; }
MagosX.com
Give a man a fish and you feed him for a day.
Teach a man to fish and you feed him for a lifetime.
Code:int main() { char *word = "hello||how||are||you||doing||there"; while (*word != '\0') { if (*word != '|') { printf("%c", *word); word++; } else if (*word == '|') { printf("%c", *word); word++; printf("\n%c", *word); word++; } } return 0; }
Last edited by OOPboredom; 03-17-2004 at 09:27 AM.
Code:#include <stdio.h> int main(void) { char word[] = "hello||how||are||you||doing||there"; char* Pointer = word; while(*Pointer != '\0') { printf("%c%s", *Pointer, *Pointer == '|' && *(Pointer+1) == '|' ? "\n" : ""); Pointer++; } return 0; }
Last edited by major_blagger; 03-17-2004 at 09:19 AM.
Great solution major. Reminds me of a professor in college that took a simple solution to a problem and wrote a small portion of code for it in C.
Each time through he would re-write the code and simplify or concatendate certain parts of the code until he got to only 2 lines of code for a solution that had 10 lines originally.
... or if you can live without the | characters....:
Code:#include <stdio.h> #include <string.h> int main(void) { char word[] = "hello||how||are||you||doing||there"; char *p; p = strtok (word, "|"); while (p) { puts (p); p = strtok (NULL, "|"); } return(0); }
When all else fails, read the instructions.
If you're posting code, use code tags: [code] /* insert code here */ [/code]