I have a few questions on string.i don't really know how to use the functions in the string library.
1)how to reverse words in string?
Eg:i input this string "reverse word" and the output will be "esrever drow"
2)how to look for substring in string?
i will enter a substring that i want and display a message to state if the word is in the string.
eg:i want to find "word" in "reverse word" and a message will be displayed saying that the substring is found in the string.
3)how to insert substring into string
i will enter a substring and the position where i want to insert it.Then the new string will be displayed on the screen.
eg:i enter "this" and i want to put in between "reverse" and "word".The new string will be " reverse this word".
C
Last Comment
umangjoshi
8/22/2022 - Mon
Kryp
> 1)how to reverse words in string?
Find the \0 at the end and work your way back to the start
Finding \0 is in effect what strlen() does.
See how you get on with problem 1 first...
Fallen_Knight
1) reverseing individual words is a bit tricky, one way to do this would be to replace all the spaces with '\0', call strrev() on the char rigth after each '\0', and the start of the string, but not the last '\0'. you'd have to keep track of the str length as not to go past the real '\0'.
2) use strstr, it does exactly that
3) well you'd have to either have enough room in your inital string or allocate a new string.
thank you for the coding for q 2 and 3.i managed to get the answers. but for q1, i wanted to reverse the characters for individual word.do u mean that i should use for loop to find '\0' then reverse the word?
Eg:
The gate to Java nirvana is near
the method outputs
ehT etag ot avaJ anavrin si raen
Fallen_Knight
ok, well heres is what i exaplined in code, untested of course, so your going to have to debug it. but this is the general solution
char *reverse words(char *str) {
int len, i;
char *cp;
Find the \0 at the end and work your way back to the start
Finding \0 is in effect what strlen() does.
See how you get on with problem 1 first...