Reverse Each Individual Word of "Hello World" String with Java

Reverse each individual word of Hello World string with Java

This should do the trick. This will iterate through each word in the source string, reverse it using StringBuilder's built-in reverse() method, and output the reversed word.

String source = "Hello World";

for (String part : source.split(" ")) {
System.out.print(new StringBuilder(part).reverse().toString());
System.out.print(" ");
}

Output:

olleH dlroW 

Notes: Commenters have correctly pointed out a few things that I thought I should mention here. This example will append an extra space to the end of the result. It also assumes your words are separated by a single space each and your sentence contains no punctuation.

Reverse a string in Java

You can use this:

new StringBuilder(hi).reverse().toString()

StringBuilder was added in Java 5. For versions prior to Java 5, the StringBuffer class can be used instead — it has the same API.

Reverse each individual word of Hello World string with Java

This should do the trick. This will iterate through each word in the source string, reverse it using StringBuilder's built-in reverse() method, and output the reversed word.

String source = "Hello World";

for (String part : source.split(" ")) {
System.out.print(new StringBuilder(part).reverse().toString());
System.out.print(" ");
}

Output:

olleH dlroW 

Notes: Commenters have correctly pointed out a few things that I thought I should mention here. This example will append an extra space to the end of the result. It also assumes your words are separated by a single space each and your sentence contains no punctuation.

Is there any method to reverse words with retaining position's case

Do it as follows:

public class Main {
public static void main(String[] args) {
System.out.println(reverseWordsRetainingPositionCase("HeLlo woRld BEn"));
}

static String reverseWordsRetainingPositionCase(String str) {
String[] words = str.split("\\s+");// Split the string on space(s)
StringBuilder sb = new StringBuilder(str);// Create a StringBuilder instance with the content of str
for (String word : words) {
// Find the word in sb and replace it with its reverse
sb.replace(sb.indexOf(word), sb.indexOf(word) + word.length(), reverseCharsRetainingPositionCase(word));
}
return sb.toString();
}

static String reverseCharsRetainingPositionCase(String word) {
StringBuilder reversedWord = new StringBuilder(word).reverse();// Reverse the word
for (int i = 0; i < word.length(); i++) {
// If the character at i in the word is in upper case, change the case of the
// character at i in the reversed word to upper case. Process the reversed word
// in the same way for lower case.
if (Character.isUpperCase(word.charAt(i))) {
reversedWord.setCharAt(i, Character.toUpperCase(reversedWord.charAt(i)));
} else if (Character.isLowerCase(word.charAt(i))) {
reversedWord.setCharAt(i, Character.toLowerCase(reversedWord.charAt(i)));
}
}
return reversedWord.toString();
}
}

Output:

OlLeh dlRow NEb

I have put enough comments in the code to make it easier for understanding. Feel free to comment in case of any doubt/issue.

How do i reverse each character in a string?

There are several problems:

  • You set current to the current position, and then iterate down to 0 append characters. Instead of going down to 0, you iterate until the beginning of the last word. Alternative, iterate until the previous ' ' character.

  • You only append something after seeing a ' ' character. What will happen at the end of the sentences? As i goes over the letters in the last word, there will be no more ' ' characters, and so the last word will never get appended. To handle this case, you would need to add some logic after the for-loop to check if there is an unwritten word, and append it reversed.

A simpler approach is to take advantage of the StringBuilder's ability to insert characters at some position.
You could track the beginning position of the current word,
and as you iterate over the characters,
insert if it's not ' ',
or else append a ' ' and reset the insertion position.

StringBuilder build = new StringBuilder();
int current = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == ' ') {
build.append(' ');
current = i + 1;
} else {
build.insert(current, c);
}
}
return build.toString();

Simple hashmap implementation in C++

Most compilers should define std::hash_map for you; in the coming C++0x standard, it will be part of the standard library as std::unordered_map. The STL Page on it is fairly standard. If you use Visual Studio, Microsoft has a page on it.

If you want to use your class as the value, not as the key, then you don't need to do anything special. All primitive types (things like int, char, bool and even char *) should "just work" as keys in a hash_map. However, for anything else you will have to define your own hashing and equality functions and then write "functors" that wrap them in a class.

Assuming your class is called MyClass and you have already defined:

size_t MyClass::HashValue() const { /* something */ }
bool MyClass::Equals(const MyClass& other) const { /* something */ }

You will need to define two functors to wrap those methods in objects.

struct MyClassHash {
size_t operator()(const MyClass& p) const {
return p.HashValue();
}
};

struct MyClassEqual {
bool operator()(const MyClass& c1, const MyClass& c2) const {
return c1.Equals(c2);
}
};

And instantiate your hash_map/hash_set as:

hash_map<MyClass, DataType, MyClassHash, MyClassEqual> my_hash_map;
hash_set<MyClass, MyClassHash, MyClassEqual> my_hash_set;

Everything should work as expected after that.



Related Topics



Leave a reply



Submit