I need help with this string problem

+1 Paul Kim · February 7, 2016
Problem 1:

Write a program that reads a string from the keyboard. If the length of the string is an even 

number, your program should split the string into two strings of equal length. If the length of 

the string is odd, your program should split the string into two strings where the first part has 

one more character than the second part. Your program should output the two strings it 

created. 

For example: 

Input: 2BeOrNotToBe

Output: 2BeOrN

otToBe

Input: ToBeOrNotToBe

Output: ToBeOrN 

otToBe


#include <stdio.h>
#include <time.h>
#include <stdlib.h>

int main()
{
char str[1000]; // Input string to be saved in str. Also assuming max length og input string can be 1000
printf("Input : ");
int i,j,counter=0;
scanf("%s",str);// saves the input string into str


for(i=0; str!='\0'; ++i); // loop to calculate the length of string str
int length=i; // length is saved in 'length' variable


char newStr2[1000]; // the second new string will be saved in newStr string
// whereas the first new string after splitting will be saved in 'str' string

if(length%2==0) // if the length is even
{

for(i=length/2;i<length;i++) //loop to create the second new string
{
newStr2[counter++]=str;
}
str[(length/2)]='\0'; // adding a null at the middle of string str, divides the str by 2
newStr2[counter]='\0';// adding a null refernce at the end of newstr2
}
else // if the length is odd
{
for(i=length/2+1;i<length;i++) //loop to create the second new string
{
newStr2[counter++]=str;
}
str[(length/2)+1]='\0';//adding a null refernce at the end of str
newStr2[counter]='\0';// adding a null refernce at the end of newstr2

}

// hence the strings are saved in str and newStr2

printf("Output:\n %s \n %s",str,newStr2); // prints the ouput
}

Post a Reply

Replies

Oldest  Newest  Rating
0 Linguist Llama · February 8, 2016
Ahh, it's one of those challenges that doesn't quite make sense, and/or attempts to teach you to solve a crippled problem in a crippled way! Let's tear this one apart...

Write a program that reads a string from the keyboard.



Firstly, what does it mean to "read a string from the keyboard"? Since a string is a sequence of characters that terminates at the first '\0', does that mean the user is expected to press the '\0' key to provide a string terminator? Which key is that, exactly? What if it's never pressed? Perhaps the question meant that the program is expected to read a word or a line (that is, a sequence of characters that terminates at the first ' ' or '\n', which corresponds to the spacebar, "return" or "enter" keys) and convert that to a string... Again, what if such a key is never pressed?

Alternatively, it's possible that the challenger meant "read ALL OF STDIN into an array, and then append a terminal value to form a string". What is meant by "read a string" is very unclear.

It's worth noting that the program you've posted will only operate on a word. It's possible that your professor might expect different behaviours. He should really be more careful setting exercises, taking particular care to set design standards that make sense.

Another problem is that there's no such concept as "the keyboard" in C; common computers have keyboards, sure, but they're implemented as a file (stdin) and as argv... There is no portable way to guarantee that the file (stdin) or argv were actually generated by a keyboard.

This brings us to a choice, whether to use stdin or argv as input. The code that you've written seems to indicate that the program only processes one field, once, so argv is most certainly more suitable than stdin from a software design perspective. However your professor is likely to state that he meant using stdin, even though that requirement isn't specified clearly (see above; he should have written "from stdin" rather than "from the keyboard"); again, he should be much more specific.

Given the lee-way from the vaguely defined exercise, here's how I'd solve this problem:

#include <stdio.h>
int main(int argc, char **argv) {
if (argc <= 1) {
puts("usage: ./app \"string\\0\"");
return 0;
}

size_t length = strlen(argv[1]),
y_length = length / 2,
x_length = y_length + length % 2;
char x[x_length + 1],
y[y_length + 1];

snprintf(x, sizeof x, "%s", argv[1]);
sprintf (y, "%s", argv[1] + x_length);

printf("%s\n%s\n", x, y);
}


There's a bit of room for optimisation here; we don't really need to create a string just to print that output. It's a bit of a premature optimisation, but the less memory we use and the less string copying we perform the more likely it is to perform well, so...

#include <stdio.h>
int main(int argc, char **argv) {
if (argc <= 1) {
puts("usage: ./app \"string\\0\"");
return 0;
}

size_t length = strlen(argv[1]),
y_length = length / 2,
x_length = y_length + length % 2;

fwrite(argv[1], 1, x_length, stdout); putchar('\n');
fwrite(argv[1] + x_length, 1, y_length, stdout); putchar('\n');
}


I can't recommend doing any of these exercises as they don't really have a point... If you want to learn programming, consider the exercises in K&R... If you want to learn program design, on the other hand, I can recommend project euler. This kind of exercise, however, falls unfortunately short for both.
0 kuldeep kanzariya · February 16, 2016
#include <stdio.h>
#include <time.h>
#include <stdlib.h>

int main()
{
        char str[1000]; // Input string to be saved in str. Also assuming max length og input string can be 1000
        printf("Input : ");
        int i,j,counter=0,length=0;
        scanf("%s",str);// saves the input string into str


        for(i=0; str!='\0'; ++i) // loop to calculate the length of string str
        length=i+1; // length is saved in 'length' variable

        char newStr2[1000]; // the second new string will be saved in newStr string
        // whereas the first new string after splitting will be saved in 'str' string

        if(length%2==0) // if the length is even
        {

                for(i=length/2;i<length;i++) //loop to create the second new string
                {
                        newStr2[counter++]=str;
                }
                str[(length/2)]='\0'; // adding a null at the middle of string str, divides the str by 2
                newStr2[counter]='\0';// adding a null refernce at the end of newstr2
        }
        else // if the length is odd
        {
                for(i=length/2+1;i<length;i++) //loop to create the second new string
                {
                        newStr2[counter++]=str;
                }
                str[(length/2)+1]='\0';//adding a null refernce at the end of str
                newStr2[counter]='\0';// adding a null refernce at the end of newstr2

        }

        // hence the strings are saved in str and newStr2

        printf("Output:\n %s \n %s \n",str,newStr2); // prints the ouput
}
  • 1

C

107,334 followers
About

One of the most popular languages of all time.

Links
Moderators
Bucky Roberts Administrator