We have to output New line for every space/gap in between strings.It's working good other than some test cases.(Range of length of string is between 0 to 1000.)
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char *s, length, i;
s = malloc(1024 * sizeof(char));
scanf("%[^\n]", s);
s = realloc(s, strlen(s) + 1);
// Write your logic to print the tokens of the sentence here.
length = strlen(s);
for (i = length - 1; i >= 0; i--) {
if (*(s + i) == ' ')
*(s + i) = '\n';
}
for (i = 0; i <= length - 1; i++) {
printf("%c", *(s + i));
}
return 0;
}
this the test case
isaegb spqe soslux feb zpkqvly jfavnxk bkyb akxc zxknsau wws hojqcxw vh vioxmqp c y vlgvzdv kg uqoddl cvjvo xkglami bnny whqnfyl gtr qfqr gezclci lwboj pgz refjok lsj qnswwvk v yv knacos ttjf ngb bobcezv tus ijgv ak dtylnij sbba wo lwojx pmxrwt fspq hao dp tnlw nmbqe ynf h rkbucw bddth v qxce ithzul if xw tzbsqq qx m ujf czkylju rhhdfj lbuph tasmexr g jzkvshc ppv scwr w qhyyeil t krvert fdz kdjtnm ioplmqy hupb bte auza lsmd aeou vrlp imxy bixzt xob arjgp arxsl pulrt mf k vtwbi xx vm wqlz pm vragv aptjle siqvy rifmztd wxytzs ukqqrxm rfr w aipunhj omwr mg j xei we encp ky e efgsun cak vdstjb gkxporp ziwmbj sut nltxhk hqil ygxmw eodsp ewr femlf u kw hmber uvfttlv vwmtmgv gohkvu syrp yayndiw qnshe gdofdyi ziszbk gb qh mrepw t hrisl lwgej wjwl b jvycei etubxfa ft fbdyjki pdjntfi odkyqi s uu ozqgiz e ryjw ekkbwvt i yqqoql w ch poco dqlfyri vltaoyt fsetj ksw jtvddy qmhs ciw qkae h ihyji iwbato xpauhh kcdbh dt zyycqgv jjo f qi zfmxq lhsd keg zmwoysl
There are several drawbacks.
The first one is the incorrect declaration of variables length
and i
that are declared as having the type char
.
char *s, length, i;
They can not store a value that is above either 127
or 255
depending on whether the type char
behaves as the type signed char
or unsigned char
.
They should be declared as having the type size_t
- the returned type of the function strlen
In fact call of this function is redundant. You can rely on the terminating zero of the input string.
There is no need to allocate and reallocate dynamically an array. You could declare an array with the automatic storage duration.
Between sub-strings of the string there can be consecutive spaces. You do not process such cases.
Pay attention to that to output sub-strings of a string does mean to change the string itself.
Here is a demonstration program that shows how the task can be performed.
#include <stdio.h>
#include <string.h>
int main(void)
{
enum { N = 1001 };
char s[N] = "";
fgets( s, sizeof( s ), stdin );
const char *delim = " \t\n";
for ( const char *p = s; *p; )
{
p += strspn( p, delim );
int n = strcspn( p, delim );
if ( n ) printf( "%*.*s\n", n, n, p );
p += n;
}
return 0;
}
If to enter for example the following string " Hello Gautam Goyal"
then the program output will be
Hello
Gautam
Goyal