Guri
Guri

Reputation: 261

How to reverse individual words?

I need to transform a string such as "my name is thomos" to "ym eman si somoht". What do I need to know in order to do that?

Upvotes: 0

Views: 1274

Answers (5)

Lijo
Lijo

Reputation: 6788

public static void main(String[] args) {

    StringBuffer buffer=new StringBuffer();
    buffer.append("my name is thomos");
    buffer.reverse();
    String str=buffer.toString();
    String arr[]=str.split(" ");
    int length=arr.length;
    for(int i=length-1;i>=0;i--)
    {
        System.out.print(arr[i]+" ");
    }


}

here we use String buffer and string because String function doesn't support the reverse function also Sting buffer doesnt support split function thats why we are taking the string value.

logic is first reverse the whole string then we will get

" somoht si eman ym"

then we will split this string using space so we will get individual string

next we just want to iterate from the end of the array and either print it or store it in a new array we will get the output as

"ym eman si somoht"

Upvotes: 0

stygma
stygma

Reputation: 523

If you are coming at this from a c-style string point of view (as I had to the first time I did this problem for homework) you might want to try some pointers. Here is the basic order of operations I went through. If you are using std::string I am pretty sure this won't work, but it might. This is really meant for c-style strings and teaching people to use pointers.

Create 2 pointers and a temp swap char.

Increment the second pointer until it references a null terminating character. Promptly deincrement it by one.

Swap what the first pointer references with what the second one references until the pointers met or pass.

Upvotes: 0

sbi
sbi

Reputation: 224179

I will not provide code, as this smells too much like homework. But I'll try to give you a nudge into the right direction.

You will first have to chop the sentence into words. You can do this by reading it from a stream (a string stream will do if you happen to have it in a string) into a string using operator>>(std::istream&,std::string&).

Then you have to reverse the individual strings. You can do so using std::reverse() from the C++ standard library.
Then all you have to do is to write the words to some output stream, putting spaces in between.

Alternatively you could output the word strings reversed, as Jerry suggested.

Upvotes: 1

Jerry Coffin
Jerry Coffin

Reputation: 490663

One possibility would be to use std::copy with a pair of std::reverse_iterators, which you can get with rbegin and rend.

Along with that, you'll probably want to use something like an std::istringstream to break the string up into words for processing.

Upvotes: 5

pauljwilliams
pauljwilliams

Reputation: 19225

Use strtok to split into words For each word, reverse the string and append to the output, along with a space

Upvotes: -2

Related Questions