nerd4life
nerd4life

Reputation: 63

Manipulating strings in C with user input

I am working on a program for my comp sci classes and the problem asks to take a command from the user and the string that. Then, use either "reverse " to reverse the string that follows or "create " to print the string that follows. The reverse output should keep the words reverse, then print the string that follows in reverse.

/* for Reverse command */
else if(strcmp(str,"reverse ") > 0)
{
    reverse(str);
    printf("Reverse of string: %s\n", str);
}

The following function is used to reverse the word:

void reverse(char *string)
{
    int length, i;
    char *begin, *end, temp;

    length = strlen(string);

    begin = string;
    end = string;

    for (i = 0 ; i < (length - 1) ; i++)
    end++;

    for (i = 0 ; i < length/2 ; i++)
    {
       temp = *end;
       *end = *begin;
       *begin = temp;

     begin++;
     end--;
    }
}

The output reverses all the words and prints. Is there a way to break off the reverse part of the string before it is passed to the reverse function?

Upvotes: 0

Views: 283

Answers (1)

Spikatrix
Spikatrix

Reputation: 20244

Before calling the function reverse, use

char *ptr=strchr(str,' ');
str=++ptr;

To cut off "reverse" from str.string.h needs to be included to use strchr.strchr returns a pointer to the first occurrence of the character ' ' in the string str, or NULL if the character is not found.ptr is incremented once before assigning it to str to remove the space from the string.

Upvotes: 1

Related Questions