reversing words in a string in c - Stack Overflow
Return the reversed words in a string, while preserving the word order
How to reverse characters in words of a string, but keep word order?
Reverse words in a string
Videos
This function should work for you:
function myFunction(string) {
return string.split("").reverse().join("").split(" ").reverse().join(" ")
};
you need to split the string by space
function reverseInPlace(str) {
var words = [];
words = str.match(/\S+/g);
var result = "";
for (var i = 0; i < words.length; i++) {
result += words[i].split('').reverse().join('') + " ";
}
return result
}
console.log(reverseInPlace("abd fhe kdj"))
I took on a very simple problem that consisted in reversing the words in a sentence. Here's what I came up with:
fn reverse_words(words: &str) -> String {
let parts: Vec<&str> = words.split(' ').rev().collect();
return parts.join(" ");
}
fn main() {
let words = "one two three";
let rev_words = reverse_words(words);
println!("words: {:?}", words);
println!("reversed: {:?}", rev_words);
}I'd be thankful if more experienced rustaceans would point out how far that is from idiomatic Rust and any other general flaws.
Here is a change to the function that makes the minimum changes to fix the bugs in the original code. Specifically made two changes: 1) Replaced the last while loop with a simple assignment to str at the bottom of the while (modified from earlier post). The right answer has already been calculated and this assignment moves the string forward without another while loop that had issues with falling off the end. 2) Put an else around the temp++ since it should not be done when a word was found or you can go off the end.
void reversed_words(char *str)
{
char word[100];
char *temp;
char *zet;
temp=str;
int k=0;
while(*temp) //processing complete string
{
if(isalnum(*temp))
{
while(isalnum(*temp)) //extracting word from string
{
word[k]=*temp;
k++;
temp++;
}
word[k]='\0';
k=0;
strrev(word); // Reverses the string
zet=word;
while (*zet) // Copying the reversed word into original string
{
*str = *zet;
zet++;
str++;
}
}
else
{
temp++;
}
str = temp;
}
}
This might be a problem:
zet = word;
while (*zet) // Copying the reversed word into original string
{
*str = *zet;
zet++;
str++;
}
while (!isalnum(*str)) // Skipping all non-alphanumeric character(s)
{
str++;
}
When it is processing the last word, it comes out of that first while loop with str pointing to either non-alphabetic junk at the end of the input string, or the '\0' terminator at the end of the string. In either case, the terminator is not alphanumeric, so the second while loop will continue reading until it finds a byte that happens to be alphanumeric, which is probably in uninitialized memory.
You could also have problems in your strrev or main functions, but you didn't post them.
It's also probably a good idea to consider what will happen if you pass this function a string with a 'word' longer than 99 characters.