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
Printable View
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++;
}
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;
}
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;
}
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);
}