简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM