Member Avatar for Member #531174

Hey guys,

As the title says, I want to know how I can reverse the characters in a string, but retaining the placement of the words as such, here's the code I used:

class reverse
{
void reverse(String s)
    {
        int l=s.length(),j=0;
        String s1="";
        for(;j<l;j++)
            {
                char a=s.charAt(j);
                if(a==' ')
                    {
                        int p=j-1;
                       for(int i=p;i>;i++)
                        {
                            char b=s.charAt();
                            s1+=b;
                        }
                    }
                }
                System.out.println(s1);
            }
        }

But in line 12, I have no clue as to what integer value to give in the for loop...can anyone help me out?

Dani AI

Generated

Several replies show ways to reverse the entire input (for example and ) or point to buffer-level reversal (). Those produce "gnirtS yM" for "My String", but the original requirement is different: reverse characters inside each word while keeping word order (result should be "yM gnirtS"). A simple, efficient approach is to scan left-to-right, append whitespace unchanged, and for each contiguous non-whitespace run append its characters in reverse order. This preserves exact spacing (including multiple spaces) and runs in linear time.

public static String reverseCharsInWords(String s) {
    if (s == null || s.isEmpty()) return s;
    StringBuilder out = new StringBuilder(s.length());
    int n = s.length(), i = 0;
    while (i < n) {
        if (Character.isWhitespace(s.charAt(i))) {
            out.append(s.charAt(i++));
        } else {
            int start = i;
            while (i < n && !Character.isWhitespace(s.charAt(i))) i++;
            for (int j = i - 1; j >= start; j--) out.append(s.charAt(j));
        }
    }
    return out.toString();
}

Notes and pitfalls: avoid building results with str = str + ch in a loop (that is O(n^2)); use a single StringBuilder as above. If input may contain supplementary Unicode characters (emoji, some CJK) reversing by char can split surrogate pairs; handle those cases with codePoints() when needed. If punctuation should remain at word ends (so "Hello," becomes "olleH," rather than ",olleH"), treat letters/digits separately (e.g. reverse only characters where Character.isLetterOrDigit or use regex to split tokens) or apply new StringBuilder(token).reverse() to precisely identified tokens. Finally, many suggestions in the thread (, ) are useful — they just need to be applied per-word rather than to the whole input.

Recommended Answers

All 6 Replies

I don't know what line 12 is because you didn't use the code tags correctly. If you had, it would have put line numbers there. Anyway:

Check out the String class's toCharArray() method. Once you get your char array, iterate backwards over it, printing out each character. If you want to store the backwards String, then do the same, except put each character in a second array, or continuously add it to a String like this: String whatever = whatever + theChar;

Here is one more solution:

public class ReverseString {

	public static void main(String args[])
	{
		String str1 = new String("My String");
	
		int strlength = str1.length();
		String reverseString="";
		for(int i=strlength-1;i>=0;i--)
		{
			reverseString+=str1.charAt(i);
		}
		System.out.println("The reverse of "+str1+" is: "+reverseString);
	}
	
}

Result: gnirtS yM

Well, yes that does reverse a string, but that still wasn't the exact question asked by the OP in 2009. They needed to also retain the word order.

There is also no reason to initialize str1 as new String() . Use a string literal instead String str1 = "My String"; This thread is marked solved by the way, so there really isn't much reason to resurrect it to post non-solutions.

import java.io.*;
import java.util.*;

class HelloString
{
    public static void main(String arg[])
    {
        Scanner scan = new Scanner(System.in);
        String s=scan.nextLine();
        int i=s.length();
        String revres="";
        for(int t=i-1;t>=0;t--)
        {
        revres=revres+s.charAt(t);
        }
        System.out.println(revres);
    }
}

Hello Chandan
Please be more careful before posting if you do not want to look foolish...
1. This thread is 4 years old and already solved
2. You didn't read the initial problem statement, so your code does not address the correct requirement
3. You didn't read the rest of the thread because umashastry did exactly the same thing 2 years ago and Ezzaral explained why that was wrong.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.