Reputation: 47
I want to input a string and then make 2 substrings, first half in first
string and second half in second
string and if the string is odd then leave the middle element.
For input given as tushar
, the output I am get is tus
and an empty line.
Here is the code:
#include <stdio.h>
#include <string.h>
int main(void) {
// your code goes here
int t;
scanf("%d", &t);
while (t--) {
char str[1000];
int i, j;
while ((getchar())!= '\n');
scanf("%[^\n]s", str);
int len = strlen(str);
char first[(len / 2) + 1];
char second[(len / 2) + 1];
for (i = 0; i < (len / 2); i++) {
first[i] = str[i];
second[i] = str[(strlen(str)) - i];
}
printf("%s\n", first);
printf("%s\n", second);
}
return 0;
}
Upvotes: 0
Views: 54
Reputation: 4864
With your code, second[0] == '\0'
. It corresponds to str[strlen(str)]
. So the second string is seen as empty effectively.
There are two others issues:
'\0'
.#include <stdio.h>
#include <string.h>
int main(void)
{
// your code goes here
int t;
scanf("%d",&t);
while(t--){
char str[1000];
int i,j;
while((getchar())!= '\n');
scanf("%s",str);
int len = strlen(str);
int position = (len + 1) / 2;
char first[(len/2)+1], second[(len/2)+1];
for (i = 0; i < (len/2); i++)
{
first[i] = str[i];
second[i] = str[position + i];
}
first[len/2] = '\0';
second[len/2] = '\0';
printf("%s\n",first);
printf("%s\n",second);
}
return 0;
}
Upvotes: 1