Remove repeated characters in a string - java

I need to write a static method that takes a String as a parameter and returns a new String obtained by replacing every instance of repeated adjacent letters with a single instance of that letter without using regular expressions. For example if I enter "maaaakkee" as a String, it returns "make".
I already tried the following code, but it doesn't seem to display the last character.
Here's my code:
import java.util.Scanner;
public class undouble {
public static void main(String [] args){
Scanner console = new Scanner(System.in);
System.out.println("enter String: ");
String str = console.nextLine();
System.out.println(removeSpaces(str));
}
public static String removeSpaces(String str){
String ourString="";
int j = 0;
for (int i=0; i<str.length()-1 ; i++){
j = i+1;
if(str.charAt(i)!=str.charAt(j)){
ourString+=str.charAt(i);
}
}
return ourString;
}
}

You could use regular expressions for that.
For instance:
String input = "ddooooonnneeeeee";
System.out.println(input.replaceAll("(.)\\1{1,}", "$1"));
Output:
done
Pattern explanation:
"(.)\\1{1,}" means any character (added to group 1) followed by itself at least once
"$1" references contents of group 1

maybe:
for (int i=1; i<str.length() ; i++){
j = i+1;
if(str.charAt(i)!=str.charAt(j)){
ourString+=str.charAt(i);
}
}

The problem is with your condition. You say compare i and i+1 in each iteration and in last iteration you have both i and j pointing to same location so it will never print the last character. Try this unleass you want to use regex to achive this:
EDIT:
public void removeSpaces(String str){
String ourString="";
for (int i=0; i<str.length()-1 ; i++){
if(i==0){
ourString = ""+str.charAt(i);
}else{
if(str.charAt(i-1) != str.charAt(i)){
ourString = ourString +str.charAt(i);
}
}
}
System.out.println(ourString);
}

if you cannot use replace or replaceAll, here is an alternative. O(2n), O(N) for stockage and O(N) for creating the string. It removes all repeated chars in the string put them in a stringbuilder.
input : abcdef , output : abcdef
input : aabbcdeef, output : cdf
private static String remove_repeated_char(String str)
{
StringBuilder result = new StringBuilder();
HashMap<Character, Integer> items = new HashMap<>();
for (int i = 0; i < str.length(); i++)
{
Character current = str.charAt(i);
Integer ocurrence = items.get(current);
if (ocurrence == null)
items.put(current, 1);
else
items.put(current, ocurrence + 1);
}
for (int i = 0; i < str.length(); i++)
{
Character current = str.charAt(i);
Integer ocurrence = items.get(current);
if (ocurrence == 1)
result.append(current);
}
return result.toString();
}

import java.util.*;
public class string2 {
public static void main(String[] args) {
//removes repeat character from array
Scanner sc=new Scanner(System.in);
StringBuffer sf=new StringBuffer();
System.out.println("enter a string");
sf.append(sc.nextLine());
System.out.println("string="+sf);
int i=0;
while( i<sf.length())
{
int j=1+i;
while(j<sf.length())
{
if(sf.charAt(i)==sf.charAt(j))
{
sf.deleteCharAt(j);
}
else
{
j=j+1;
}
}
i=i+1;
}
System.out.println("string="+sf);
}
}

Input AABBBccDDD, Output BD
Input ABBCDDA, Outout C
private String reducedString(String s){
char[] arr = s.toCharArray();
String newString = "";
Map<Character,Integer> map = new HashMap<Character,Integer>();
map.put(arr[0],1);
for(int index=1;index<s.length();index++)
{
Character key = arr[index];
int value;
if(map.get(key) ==null)
{
value =0;
}
else
{
value = map.get(key);
}
value = value+1;
map.put(key,value);
}
Set<Character> keyset = map.keySet();
for(Character c: keyset)
{
int value = map.get(c);
if(value%2 !=0)
{
newString+=c;
}
}
newString = newString.equals("")?"Empty String":newString;
return newString;
}

public class RemoveDuplicateCharecterInString {
static String input = new String("abbbbbbbbbbbbbbbbccccd");
static String output = "";
public static void main(String[] args)
{
// TODO Auto-generated method stub
for (int i = 0; i < input.length(); i++) {
char temp = input.charAt(i);
boolean check = false;
for (int j = 0; j < output.length(); j++) {
if (output.charAt(j) == input.charAt(i)) {
check = true;
}
}
if (!check) {
output = output + input.charAt(i);
}
}
System.out.println(" " + output);
}
}
Answer : abcd

public class RepeatedChar {
public static void main(String[] args) {
String rS = "maaaakkee";
String outCome= rS.charAt(0)+"";
int count =0;
char [] cA =rS.toCharArray();
for(int i =0; i+1<cA.length; ++i) {
if(rS.charAt(i) != rS.charAt(i+1)) {
outCome += rS.charAt(i+1);
}
}
System.out.println(outCome);
}
}

TO WRITE JAVA PROGRAM TO REMOVE REPEATED CHARACTERS:
package replace;
public class removingrepeatedcharacters
{
public static void main(String...args){
int i,j=0,count=0;
String str="noordeen";
String str2="noordeen";
char[] ch=str.toCharArray();
for(i=0;i<=5;i++)
{
count=0;
for(j=0;j<str2.length();j++)
{
if(ch[i]==str2.charAt(j))
{
count++;
System.out.println("at the index "+j +"position "+ch[i]+ "+ count is"+count);
if(count>=2){
str=str2;
str2=str.replaceFirst(Character.toString(ch[j]),Character.toString(' '));
}
System.out.println("after replacing " +str2);
}
}
}
}
}

String outstr = "";
String outstring = "";
for(int i = 0; i < str.length() - 1; i++) {
if(str.charAt(i) != str.charAt(i + 1)) {
outstr = outstr + str.charAt(i);
}
outstring = outstr + str.charAt(i);
}
System.out.println(outstring);

public static void remove_duplicates(String str){
String outstr="";
String outstring="";
for(int i=0;i<str.length()-1;i++) {
if(str.charAt(i)!=str.charAt(i+1)) {
outstr=outstr+str.charAt(i);
}
outstring=outstr+str.charAt(i);
}
System.out.println(outstring);
}

More fun with java 7:
System.out.println("11223344445555".replaceAll("(?<nums>.+)\\k<nums>+","${nums}"));
No more cryptic numbers in regexes.

public static String removeDuplicates(String str) {
String str2 = "" + str.charAt(0);
for (int i = 1; i < str.length(); i++) {
if (str.charAt(i - 1) == str.charAt(i) && i != 0) {
continue;
}
str2 = str2 + str.charAt(i);
}
return str2;
}

Related

Rewriting the String in Reverse [duplicate]

I have "Hello World" kept in a String variable named hi.
I need to print it, but reversed.
How can I do this? I understand there is some kind of a function already built-in into Java that does that.
Related: Reverse each individual word of “Hello World” string with 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.
For Online Judges problems that does not allow StringBuilder or StringBuffer, you can do it in place using char[] as following:
public static String reverse(String input){
char[] in = input.toCharArray();
int begin=0;
int end=in.length-1;
char temp;
while(end>begin){
temp = in[begin];
in[begin]=in[end];
in[end] = temp;
end--;
begin++;
}
return new String(in);
}
public static String reverseIt(String source) {
int i, len = source.length();
StringBuilder dest = new StringBuilder(len);
for (i = (len - 1); i >= 0; i--){
dest.append(source.charAt(i));
}
return dest.toString();
}
http://www.java2s.com/Code/Java/Language-Basics/ReverseStringTest.htm
String string="whatever";
String reverse = new StringBuffer(string).reverse().toString();
System.out.println(reverse);
I am doing this by using the following two ways:
Reverse string by CHARACTERS:
public static void main(String[] args) {
// Using traditional approach
String result="";
for(int i=string.length()-1; i>=0; i--) {
result = result + string.charAt(i);
}
System.out.println(result);
// Using StringBuffer class
StringBuffer buffer = new StringBuffer(string);
System.out.println(buffer.reverse());
}
Reverse string by WORDS:
public static void reverseStringByWords(String string) {
StringBuilder stringBuilder = new StringBuilder();
String[] words = string.split(" ");
for (int j = words.length-1; j >= 0; j--) {
stringBuilder.append(words[j]).append(' ');
}
System.out.println("Reverse words: " + stringBuilder);
}
Take a look at the Java 6 API under StringBuffer
String s = "sample";
String result = new StringBuffer(s).reverse().toString();
Here is an example using recursion:
public void reverseString() {
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String reverseAlphabet = reverse(alphabet, alphabet.length()-1);
}
String reverse(String stringToReverse, int index){
if(index == 0){
return stringToReverse.charAt(0) + "";
}
char letter = stringToReverse.charAt(index);
return letter + reverse(stringToReverse, index-1);
}
Here is a low level solution:
import java.util.Scanner;
public class class1 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String inpStr = in.nextLine();
System.out.println("Original String :" + inpStr);
char temp;
char[] arr = inpStr.toCharArray();
int len = arr.length;
for(int i=0; i<(inpStr.length())/2; i++,len--){
temp = arr[i];
arr[i] = arr[len-1];
arr[len-1] = temp;
}
System.out.println("Reverse String :" + String.valueOf(arr));
}
}
I tried, just for fun, by using a Stack. Here my code:
public String reverseString(String s) {
Stack<Character> stack = new Stack<>();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
stack.push(s.charAt(i));
}
while (!stack.empty()) {
sb.append(stack.pop());
}
return sb.toString();
}
Since the below method (using XOR) to reverse a string is not listed, I am attaching this method to reverse a string.
The Algorithm is based on :
1.(A XOR B) XOR B = A
2.(A XOR B) XOR A = B
Code snippet:
public class ReverseUsingXOR {
public static void main(String[] args) {
String str = "prateek";
reverseUsingXOR(str.toCharArray());
}
/*Example:
* str= prateek;
* str[low]=p;
* str[high]=k;
* str[low]=p^k;
* str[high]=(p^k)^k =p;
* str[low]=(p^k)^p=k;
*
* */
public static void reverseUsingXOR(char[] str) {
int low = 0;
int high = str.length - 1;
while (low < high) {
str[low] = (char) (str[low] ^ str[high]);
str[high] = (char) (str[low] ^ str[high]);
str[low] = (char) (str[low] ^ str[high]);
low++;
high--;
}
//display reversed string
for (int i = 0; i < str.length; i++) {
System.out.print(str[i]);
}
}
}
Output:
keetarp
As others have pointed out the preferred way is to use:
new StringBuilder(hi).reverse().toString()
But if you want to implement this by yourself, I'm afraid that the rest of responses have flaws.
The reason is that String represents a list of Unicode points, encoded in a char[] array according to the variable-length encoding: UTF-16.
This means some code points use a single element of the array (one code unit) but others use two of them, so there might be pairs of characters that must be treated as a single unit (consecutive "high" and "low" surrogates).
public static String reverseString(String s) {
char[] chars = new char[s.length()];
boolean twoCharCodepoint = false;
for (int i = 0; i < s.length(); i++) {
chars[s.length() - 1 - i] = s.charAt(i);
if (twoCharCodepoint) {
swap(chars, s.length() - 1 - i, s.length() - i);
}
twoCharCodepoint = !Character.isBmpCodePoint(s.codePointAt(i));
}
return new String(chars);
}
private static void swap(char[] array, int i, int j) {
char temp = array[i];
array[i] = array[j];
array[j] = temp;
}
public static void main(String[] args) throws Exception {
FileOutputStream fos = new FileOutputStream("C:/temp/reverse-string.txt");
StringBuilder sb = new StringBuilder("Linear B Syllable B008 A: ");
sb.appendCodePoint(65536); //http://unicode-table.com/es/#10000
sb.append(".");
fos.write(sb.toString().getBytes("UTF-16"));
fos.write("\n".getBytes("UTF-16"));
fos.write(reverseString(sb.toString()).getBytes("UTF-16"));
}
Using charAt() method
String name = "gaurav";
String reversedString = "";
for(int i = name.length()-1; i>=0; i--){
reversedString = reversedString + name.charAt(i);
}
System.out.println(reversedString);
Using toCharArray() method
String name = "gaurav";
char [] stringCharArray = name.toCharArray();
String reversedString = "";
for(int i = stringCharArray.length-1; i>=0; i--) {
reversedString = reversedString + stringCharArray[i];
}
System.out.println(reversedString);
Using reverse() method of the Stringbuilder
String name = "gaurav";
String reversedString = new StringBuilder(name).reverse().toString();
System.out.println(reversedString);
Check https://coderolls.com/reverse-a-string-in-java/
It is very simple in minimum code of lines
public class ReverseString {
public static void main(String[] args) {
String s1 = "neelendra";
for(int i=s1.length()-1;i>=0;i--)
{
System.out.print(s1.charAt(i));
}
}
}
This did the trick for me
public static void main(String[] args) {
String text = "abcdefghijklmnopqrstuvwxyz";
for (int i = (text.length() - 1); i >= 0; i--) {
System.out.print(text.charAt(i));
}
}
1. Using Character Array:
public String reverseString(String inputString) {
char[] inputStringArray = inputString.toCharArray();
String reverseString = "";
for (int i = inputStringArray.length - 1; i >= 0; i--) {
reverseString += inputStringArray[i];
}
return reverseString;
}
2. Using StringBuilder:
public String reverseString(String inputString) {
StringBuilder stringBuilder = new StringBuilder(inputString);
stringBuilder = stringBuilder.reverse();
return stringBuilder.toString();
}
OR
return new StringBuilder(inputString).reverse().toString();
System.out.print("Please enter your name: ");
String name = keyboard.nextLine();
String reverse = new StringBuffer(name).reverse().toString();
String rev = reverse.toLowerCase();
System.out.println(rev);
I used this method to turn names backwards and into lower case.
One natural way to reverse a String is to use a StringTokenizer and a stack. Stack is a class that implements an easy-to-use last-in, first-out (LIFO) stack of objects.
String s = "Hello My name is Sufiyan";
Put it in the stack frontwards
Stack<String> myStack = new Stack<>();
StringTokenizer st = new StringTokenizer(s);
while (st.hasMoreTokens()) {
myStack.push(st.nextToken());
}
Print the stack backwards
System.out.print('"' + s + '"' + " backwards by word is:\n\t\"");
while (!myStack.empty()) {
System.out.print(myStack.pop());
System.out.print(' ');
}
System.out.println('"');
public String reverse(String s) {
String reversedString = "";
for(int i=s.length(); i>0; i--) {
reversedString += s.charAt(i-1);
}
return reversedString;
}
public class Test {
public static void main(String args[]) {
StringBuffer buffer = new StringBuffer("Game Plan");
buffer.reverse();
System.out.println(buffer);
}
}
All above solution is too good but here I am making reverse string using recursive programming.
This is helpful for who is looking recursive way of doing reverse string.
public class ReversString {
public static void main(String args[]) {
char s[] = "Dhiral Pandya".toCharArray();
String r = new String(reverse(0, s));
System.out.println(r);
}
public static char[] reverse(int i, char source[]) {
if (source.length / 2 == i) {
return source;
}
char t = source[i];
source[i] = source[source.length - 1 - i];
source[source.length - 1 - i] = t;
i++;
return reverse(i, source);
}
}
You can also try this:
public class StringReverse {
public static void main(String[] args) {
String str = "Dogs hates cats";
StringBuffer sb = new StringBuffer(str);
System.out.println(sb.reverse());
}
}
Procedure :
We can use split() to split the string .Then use reverse loop and add the characters.
Code snippet:
class test
{
public static void main(String args[])
{
String str = "world";
String[] split= str.split("");
String revers = "";
for (int i = split.length-1; i>=0; i--)
{
revers += split[i];
}
System.out.printf("%s", revers);
}
}
//output : dlrow
It gets the value you typed and returns it reversed ;)
public static String reverse (String a){
char[] rarray = a.toCharArray();
String finalvalue = "";
for (int i = 0; i < rarray.length; i++)
{
finalvalue += rarray[rarray.length - 1 - i];
}
return finalvalue;
}
public String reverseWords(String s) {
String reversedWords = "";
if(s.length()<=0) {
return reversedWords;
}else if(s.length() == 1){
if(s == " "){
return "";
}
return s;
}
char arr[] = s.toCharArray();
int j = arr.length-1;
while(j >= 0 ){
if( arr[j] == ' '){
reversedWords+=arr[j];
}else{
String temp="";
while(j>=0 && arr[j] != ' '){
temp+=arr[j];
j--;
}
j++;
temp = reverseWord(temp);
reversedWords+=temp;
}
j--;
}
String[] chk = reversedWords.split(" ");
if(chk == null || chk.length == 0){
return "";
}
return reversedWords;
}
public String reverseWord(String s){
char[] arr = s.toCharArray();
for(int i=0,j=arr.length-1;i<=j;i++,j--){
char tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
return String.valueOf(arr);
}
public static void main(String[] args) {
String str = "Prashant";
int len = str.length();
char[] c = new char[len];
for (int j = len - 1, i = 0; j >= 0; j--, i++) {
c[i] = str.charAt(j);
}
str = String.copyValueOf(c);
System.out.println(str);
}
public void reverString(){
System.out.println("Enter value");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
try{
String str=br.readLine();
char[] charArray=str.toCharArray();
for(int i=charArray.length-1; i>=0; i--){
System.out.println(charArray[i]);
}
}
catch(IOException ex){
}
recursion:
public String stringReverse(String string) {
if (string == null || string.length() == 0) {
return string;
}
return stringReverse(string.substring(1)) + string.charAt(0);
}
Sequence of characters (or) StringString's Family:
String testString = "Yashwanth#777"; // ~1 1⁄4→D800₁₆«2²⁰
Using Java 8 Stream API
First we convert String into stream by using method CharSequence.chars(), then we use the method IntStream.range to generate a sequential stream of numbers. Then we map this sequence of stream into String.
public static String reverseString_Stream(String str) {
IntStream cahrStream = str.chars();
final int[] array = cahrStream.map( x -> x ).toArray();
int from = 0, upTo = array.length;
IntFunction<String> reverseMapper = (i) -> ( Character.toString((char) array[ (upTo - i) + (from - 1) ]) );
String reverseString = IntStream.range(from, upTo) // for (int i = from; i < upTo ; i++) { ... }
.mapToObj( reverseMapper ) // array[ lastElement ]
.collect(Collectors.joining()) // Joining stream of elements together into a String.
.toString(); // This object (which is already a string!) is itself returned.
System.out.println("Reverse Stream as String : "+ reverseString);
return reverseString;
}
Using a Traditional for Loop
If you want to reverse the string then we need to follow these steps.
Convert String into an Array of Characters.
Iterate over an array in reverse order, append each Character to temporary string variable until the last character.
public static String reverseString( String reverse ) {
if( reverse != null && reverse != "" && reverse.length() > 0 ) {
char[] arr = reverse.toCharArray();
String temp = "";
for( int i = arr.length-1; i >= 0; i-- ) {
temp += arr[i];
}
System.out.println("Reverse String : "+ temp);
}
return null;
}
Easy way to Use reverse method provided form StringBuffer or StringBuilder Classes
StringBuilder and StringBuffer are mutable sequence of characters. That means one can change the value of these object's.
StringBuffer buffer = new StringBuffer(str);
System.out.println("StringBuffer - reverse : "+ buffer.reverse() );
String builderString = (new StringBuilder(str)).reverse().toString;
System.out.println("StringBuilder generated reverse String : "+ builderString );
StringBuffer has the same methods as the StringBuilder, but each method in StringBuffer is synchronized so it is thread safe.
public static String revString(String str){
char[] revCharArr = str.toCharArray();
for (int i=0; i< str.length()/2; i++){
char f = revCharArr[i];
char l = revCharArr[str.length()-i-1];
revCharArr[i] = l;
revCharArr[str.length()-i-1] = f;
}
String revStr = new String(revCharArr);
return revStr;
}
Simple For loop in java
public void reverseString(char[] s) {
int length = s.length;
for (int i = 0; i < s.length / 2; i++) {
// swaping character
char temp = s[length - i - 1];
s[length - i - 1] = s[i];
s[i] = temp;
}
}

Is reversing a string this way bad practice? [Java] [duplicate]

I have "Hello World" kept in a String variable named hi.
I need to print it, but reversed.
How can I do this? I understand there is some kind of a function already built-in into Java that does that.
Related: Reverse each individual word of “Hello World” string with 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.
For Online Judges problems that does not allow StringBuilder or StringBuffer, you can do it in place using char[] as following:
public static String reverse(String input){
char[] in = input.toCharArray();
int begin=0;
int end=in.length-1;
char temp;
while(end>begin){
temp = in[begin];
in[begin]=in[end];
in[end] = temp;
end--;
begin++;
}
return new String(in);
}
public static String reverseIt(String source) {
int i, len = source.length();
StringBuilder dest = new StringBuilder(len);
for (i = (len - 1); i >= 0; i--){
dest.append(source.charAt(i));
}
return dest.toString();
}
http://www.java2s.com/Code/Java/Language-Basics/ReverseStringTest.htm
String string="whatever";
String reverse = new StringBuffer(string).reverse().toString();
System.out.println(reverse);
I am doing this by using the following two ways:
Reverse string by CHARACTERS:
public static void main(String[] args) {
// Using traditional approach
String result="";
for(int i=string.length()-1; i>=0; i--) {
result = result + string.charAt(i);
}
System.out.println(result);
// Using StringBuffer class
StringBuffer buffer = new StringBuffer(string);
System.out.println(buffer.reverse());
}
Reverse string by WORDS:
public static void reverseStringByWords(String string) {
StringBuilder stringBuilder = new StringBuilder();
String[] words = string.split(" ");
for (int j = words.length-1; j >= 0; j--) {
stringBuilder.append(words[j]).append(' ');
}
System.out.println("Reverse words: " + stringBuilder);
}
Take a look at the Java 6 API under StringBuffer
String s = "sample";
String result = new StringBuffer(s).reverse().toString();
Here is an example using recursion:
public void reverseString() {
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String reverseAlphabet = reverse(alphabet, alphabet.length()-1);
}
String reverse(String stringToReverse, int index){
if(index == 0){
return stringToReverse.charAt(0) + "";
}
char letter = stringToReverse.charAt(index);
return letter + reverse(stringToReverse, index-1);
}
Here is a low level solution:
import java.util.Scanner;
public class class1 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String inpStr = in.nextLine();
System.out.println("Original String :" + inpStr);
char temp;
char[] arr = inpStr.toCharArray();
int len = arr.length;
for(int i=0; i<(inpStr.length())/2; i++,len--){
temp = arr[i];
arr[i] = arr[len-1];
arr[len-1] = temp;
}
System.out.println("Reverse String :" + String.valueOf(arr));
}
}
I tried, just for fun, by using a Stack. Here my code:
public String reverseString(String s) {
Stack<Character> stack = new Stack<>();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
stack.push(s.charAt(i));
}
while (!stack.empty()) {
sb.append(stack.pop());
}
return sb.toString();
}
Since the below method (using XOR) to reverse a string is not listed, I am attaching this method to reverse a string.
The Algorithm is based on :
1.(A XOR B) XOR B = A
2.(A XOR B) XOR A = B
Code snippet:
public class ReverseUsingXOR {
public static void main(String[] args) {
String str = "prateek";
reverseUsingXOR(str.toCharArray());
}
/*Example:
* str= prateek;
* str[low]=p;
* str[high]=k;
* str[low]=p^k;
* str[high]=(p^k)^k =p;
* str[low]=(p^k)^p=k;
*
* */
public static void reverseUsingXOR(char[] str) {
int low = 0;
int high = str.length - 1;
while (low < high) {
str[low] = (char) (str[low] ^ str[high]);
str[high] = (char) (str[low] ^ str[high]);
str[low] = (char) (str[low] ^ str[high]);
low++;
high--;
}
//display reversed string
for (int i = 0; i < str.length; i++) {
System.out.print(str[i]);
}
}
}
Output:
keetarp
As others have pointed out the preferred way is to use:
new StringBuilder(hi).reverse().toString()
But if you want to implement this by yourself, I'm afraid that the rest of responses have flaws.
The reason is that String represents a list of Unicode points, encoded in a char[] array according to the variable-length encoding: UTF-16.
This means some code points use a single element of the array (one code unit) but others use two of them, so there might be pairs of characters that must be treated as a single unit (consecutive "high" and "low" surrogates).
public static String reverseString(String s) {
char[] chars = new char[s.length()];
boolean twoCharCodepoint = false;
for (int i = 0; i < s.length(); i++) {
chars[s.length() - 1 - i] = s.charAt(i);
if (twoCharCodepoint) {
swap(chars, s.length() - 1 - i, s.length() - i);
}
twoCharCodepoint = !Character.isBmpCodePoint(s.codePointAt(i));
}
return new String(chars);
}
private static void swap(char[] array, int i, int j) {
char temp = array[i];
array[i] = array[j];
array[j] = temp;
}
public static void main(String[] args) throws Exception {
FileOutputStream fos = new FileOutputStream("C:/temp/reverse-string.txt");
StringBuilder sb = new StringBuilder("Linear B Syllable B008 A: ");
sb.appendCodePoint(65536); //http://unicode-table.com/es/#10000
sb.append(".");
fos.write(sb.toString().getBytes("UTF-16"));
fos.write("\n".getBytes("UTF-16"));
fos.write(reverseString(sb.toString()).getBytes("UTF-16"));
}
Using charAt() method
String name = "gaurav";
String reversedString = "";
for(int i = name.length()-1; i>=0; i--){
reversedString = reversedString + name.charAt(i);
}
System.out.println(reversedString);
Using toCharArray() method
String name = "gaurav";
char [] stringCharArray = name.toCharArray();
String reversedString = "";
for(int i = stringCharArray.length-1; i>=0; i--) {
reversedString = reversedString + stringCharArray[i];
}
System.out.println(reversedString);
Using reverse() method of the Stringbuilder
String name = "gaurav";
String reversedString = new StringBuilder(name).reverse().toString();
System.out.println(reversedString);
Check https://coderolls.com/reverse-a-string-in-java/
It is very simple in minimum code of lines
public class ReverseString {
public static void main(String[] args) {
String s1 = "neelendra";
for(int i=s1.length()-1;i>=0;i--)
{
System.out.print(s1.charAt(i));
}
}
}
This did the trick for me
public static void main(String[] args) {
String text = "abcdefghijklmnopqrstuvwxyz";
for (int i = (text.length() - 1); i >= 0; i--) {
System.out.print(text.charAt(i));
}
}
1. Using Character Array:
public String reverseString(String inputString) {
char[] inputStringArray = inputString.toCharArray();
String reverseString = "";
for (int i = inputStringArray.length - 1; i >= 0; i--) {
reverseString += inputStringArray[i];
}
return reverseString;
}
2. Using StringBuilder:
public String reverseString(String inputString) {
StringBuilder stringBuilder = new StringBuilder(inputString);
stringBuilder = stringBuilder.reverse();
return stringBuilder.toString();
}
OR
return new StringBuilder(inputString).reverse().toString();
System.out.print("Please enter your name: ");
String name = keyboard.nextLine();
String reverse = new StringBuffer(name).reverse().toString();
String rev = reverse.toLowerCase();
System.out.println(rev);
I used this method to turn names backwards and into lower case.
One natural way to reverse a String is to use a StringTokenizer and a stack. Stack is a class that implements an easy-to-use last-in, first-out (LIFO) stack of objects.
String s = "Hello My name is Sufiyan";
Put it in the stack frontwards
Stack<String> myStack = new Stack<>();
StringTokenizer st = new StringTokenizer(s);
while (st.hasMoreTokens()) {
myStack.push(st.nextToken());
}
Print the stack backwards
System.out.print('"' + s + '"' + " backwards by word is:\n\t\"");
while (!myStack.empty()) {
System.out.print(myStack.pop());
System.out.print(' ');
}
System.out.println('"');
public String reverse(String s) {
String reversedString = "";
for(int i=s.length(); i>0; i--) {
reversedString += s.charAt(i-1);
}
return reversedString;
}
public class Test {
public static void main(String args[]) {
StringBuffer buffer = new StringBuffer("Game Plan");
buffer.reverse();
System.out.println(buffer);
}
}
All above solution is too good but here I am making reverse string using recursive programming.
This is helpful for who is looking recursive way of doing reverse string.
public class ReversString {
public static void main(String args[]) {
char s[] = "Dhiral Pandya".toCharArray();
String r = new String(reverse(0, s));
System.out.println(r);
}
public static char[] reverse(int i, char source[]) {
if (source.length / 2 == i) {
return source;
}
char t = source[i];
source[i] = source[source.length - 1 - i];
source[source.length - 1 - i] = t;
i++;
return reverse(i, source);
}
}
You can also try this:
public class StringReverse {
public static void main(String[] args) {
String str = "Dogs hates cats";
StringBuffer sb = new StringBuffer(str);
System.out.println(sb.reverse());
}
}
Procedure :
We can use split() to split the string .Then use reverse loop and add the characters.
Code snippet:
class test
{
public static void main(String args[])
{
String str = "world";
String[] split= str.split("");
String revers = "";
for (int i = split.length-1; i>=0; i--)
{
revers += split[i];
}
System.out.printf("%s", revers);
}
}
//output : dlrow
It gets the value you typed and returns it reversed ;)
public static String reverse (String a){
char[] rarray = a.toCharArray();
String finalvalue = "";
for (int i = 0; i < rarray.length; i++)
{
finalvalue += rarray[rarray.length - 1 - i];
}
return finalvalue;
}
public String reverseWords(String s) {
String reversedWords = "";
if(s.length()<=0) {
return reversedWords;
}else if(s.length() == 1){
if(s == " "){
return "";
}
return s;
}
char arr[] = s.toCharArray();
int j = arr.length-1;
while(j >= 0 ){
if( arr[j] == ' '){
reversedWords+=arr[j];
}else{
String temp="";
while(j>=0 && arr[j] != ' '){
temp+=arr[j];
j--;
}
j++;
temp = reverseWord(temp);
reversedWords+=temp;
}
j--;
}
String[] chk = reversedWords.split(" ");
if(chk == null || chk.length == 0){
return "";
}
return reversedWords;
}
public String reverseWord(String s){
char[] arr = s.toCharArray();
for(int i=0,j=arr.length-1;i<=j;i++,j--){
char tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
return String.valueOf(arr);
}
public static void main(String[] args) {
String str = "Prashant";
int len = str.length();
char[] c = new char[len];
for (int j = len - 1, i = 0; j >= 0; j--, i++) {
c[i] = str.charAt(j);
}
str = String.copyValueOf(c);
System.out.println(str);
}
public void reverString(){
System.out.println("Enter value");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
try{
String str=br.readLine();
char[] charArray=str.toCharArray();
for(int i=charArray.length-1; i>=0; i--){
System.out.println(charArray[i]);
}
}
catch(IOException ex){
}
recursion:
public String stringReverse(String string) {
if (string == null || string.length() == 0) {
return string;
}
return stringReverse(string.substring(1)) + string.charAt(0);
}
Sequence of characters (or) StringString's Family:
String testString = "Yashwanth#777"; // ~1 1⁄4→D800₁₆«2²⁰
Using Java 8 Stream API
First we convert String into stream by using method CharSequence.chars(), then we use the method IntStream.range to generate a sequential stream of numbers. Then we map this sequence of stream into String.
public static String reverseString_Stream(String str) {
IntStream cahrStream = str.chars();
final int[] array = cahrStream.map( x -> x ).toArray();
int from = 0, upTo = array.length;
IntFunction<String> reverseMapper = (i) -> ( Character.toString((char) array[ (upTo - i) + (from - 1) ]) );
String reverseString = IntStream.range(from, upTo) // for (int i = from; i < upTo ; i++) { ... }
.mapToObj( reverseMapper ) // array[ lastElement ]
.collect(Collectors.joining()) // Joining stream of elements together into a String.
.toString(); // This object (which is already a string!) is itself returned.
System.out.println("Reverse Stream as String : "+ reverseString);
return reverseString;
}
Using a Traditional for Loop
If you want to reverse the string then we need to follow these steps.
Convert String into an Array of Characters.
Iterate over an array in reverse order, append each Character to temporary string variable until the last character.
public static String reverseString( String reverse ) {
if( reverse != null && reverse != "" && reverse.length() > 0 ) {
char[] arr = reverse.toCharArray();
String temp = "";
for( int i = arr.length-1; i >= 0; i-- ) {
temp += arr[i];
}
System.out.println("Reverse String : "+ temp);
}
return null;
}
Easy way to Use reverse method provided form StringBuffer or StringBuilder Classes
StringBuilder and StringBuffer are mutable sequence of characters. That means one can change the value of these object's.
StringBuffer buffer = new StringBuffer(str);
System.out.println("StringBuffer - reverse : "+ buffer.reverse() );
String builderString = (new StringBuilder(str)).reverse().toString;
System.out.println("StringBuilder generated reverse String : "+ builderString );
StringBuffer has the same methods as the StringBuilder, but each method in StringBuffer is synchronized so it is thread safe.
public static String revString(String str){
char[] revCharArr = str.toCharArray();
for (int i=0; i< str.length()/2; i++){
char f = revCharArr[i];
char l = revCharArr[str.length()-i-1];
revCharArr[i] = l;
revCharArr[str.length()-i-1] = f;
}
String revStr = new String(revCharArr);
return revStr;
}
Simple For loop in java
public void reverseString(char[] s) {
int length = s.length;
for (int i = 0; i < s.length / 2; i++) {
// swaping character
char temp = s[length - i - 1];
s[length - i - 1] = s[i];
s[i] = temp;
}
}

Reverse each word of a string without altering their position(Without using inbuilt fucntion)

I want to reverse each individual word of a String in Java in different different sitautions (not the entire string, just each individual word).
Example1: if input String is "This is a test" then the output should be "sihT si a tset".
Example2: if input String is "This is a test" then the output should be "sihT si a tset".
[When there is more than one space between some words]
Please also provide algorithm for understanding
What I have tried so far
class reverseAString
{
public static void main(String args[])
{
String str= "Test the product";
String strArr[]= str.split(" ");
for(int i=0;i<=strArr.length-1;i++)
{
for(int j=strArr[i].length()-1; j>=0;j--)
{
System.out.print(strArr[i].charAt(j));
}
System.out.printf(" ");
}
}
}
---------
public String reverseWordByWord(String str){
int strLeng = str.length()-1;
String reverse = "", temp = "";
for(int i = 0; i <= strLeng; i++){
temp += str.charAt(i);
if((str.charAt(i) == ' ') || (i == strLeng)){
for(int j = temp.length()-1; j >= 0; j--){
reverse += temp.charAt(j);
if((j == 0) && (i != strLeng))
reverse += " ";
}
temp = "";
}
}
return reverse;
}
This approach is much more succinct.
class StringRev{
public static void main(String args[]){
String str[] = "Test the product".split(" ");
String finalStr="";
for(int i = str.length-1; i>= 0 ;i--){
finalStr += str[i]+" ";
}
System.out.println(finalStr);
}
}
public static void main(String arg[]) {
System.out.println(reverseWords("This is a test"));
}
// function to reverse each word
public static String reverseWords(String input) {
String result = null;
StringBuffer strBuffer = new StringBuffer();
String split[] = input.split(" ");
for (String temp : split) {
if (temp != " ") {
strBuffer.append(reverse(temp));
strBuffer.append(" ");
} else {
strBuffer.append(" ");
}
}
result = strBuffer.toString();
return result;
}
// function to reverse individual word
public static String reverse(String input) {
StringBuffer strBuffer = new StringBuffer();
char[] charArray = input.toCharArray();
for (int j = charArray.length - 1; j >= 0; j--) {
strBuffer.append(charArray[j]);
}
return strBuffer.toString();
}
Split complete string on basis of space
Then convert each string to character array and reverse
individual word.
It's been a long time since I've touch Java, but here's the algorithm.
String stringToReverse = "This is a Test";
String finalString = "";
Stack word = new Stack;
for(int i = 0; i < stringToReverse.length; i++){
char chr = stringToReverse[i];
if(chr == " " || i == (stringToReverse.length - 1)){
while(word.count > 0){
finalString += word.pop();
}
finalString += chr;
}else{
word.push(chr);
}
}

Reverseing a string in java [duplicate]

I have "Hello World" kept in a String variable named hi.
I need to print it, but reversed.
How can I do this? I understand there is some kind of a function already built-in into Java that does that.
Related: Reverse each individual word of “Hello World” string with 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.
For Online Judges problems that does not allow StringBuilder or StringBuffer, you can do it in place using char[] as following:
public static String reverse(String input){
char[] in = input.toCharArray();
int begin=0;
int end=in.length-1;
char temp;
while(end>begin){
temp = in[begin];
in[begin]=in[end];
in[end] = temp;
end--;
begin++;
}
return new String(in);
}
public static String reverseIt(String source) {
int i, len = source.length();
StringBuilder dest = new StringBuilder(len);
for (i = (len - 1); i >= 0; i--){
dest.append(source.charAt(i));
}
return dest.toString();
}
http://www.java2s.com/Code/Java/Language-Basics/ReverseStringTest.htm
String string="whatever";
String reverse = new StringBuffer(string).reverse().toString();
System.out.println(reverse);
I am doing this by using the following two ways:
Reverse string by CHARACTERS:
public static void main(String[] args) {
// Using traditional approach
String result="";
for(int i=string.length()-1; i>=0; i--) {
result = result + string.charAt(i);
}
System.out.println(result);
// Using StringBuffer class
StringBuffer buffer = new StringBuffer(string);
System.out.println(buffer.reverse());
}
Reverse string by WORDS:
public static void reverseStringByWords(String string) {
StringBuilder stringBuilder = new StringBuilder();
String[] words = string.split(" ");
for (int j = words.length-1; j >= 0; j--) {
stringBuilder.append(words[j]).append(' ');
}
System.out.println("Reverse words: " + stringBuilder);
}
Take a look at the Java 6 API under StringBuffer
String s = "sample";
String result = new StringBuffer(s).reverse().toString();
Here is an example using recursion:
public void reverseString() {
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String reverseAlphabet = reverse(alphabet, alphabet.length()-1);
}
String reverse(String stringToReverse, int index){
if(index == 0){
return stringToReverse.charAt(0) + "";
}
char letter = stringToReverse.charAt(index);
return letter + reverse(stringToReverse, index-1);
}
Here is a low level solution:
import java.util.Scanner;
public class class1 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String inpStr = in.nextLine();
System.out.println("Original String :" + inpStr);
char temp;
char[] arr = inpStr.toCharArray();
int len = arr.length;
for(int i=0; i<(inpStr.length())/2; i++,len--){
temp = arr[i];
arr[i] = arr[len-1];
arr[len-1] = temp;
}
System.out.println("Reverse String :" + String.valueOf(arr));
}
}
I tried, just for fun, by using a Stack. Here my code:
public String reverseString(String s) {
Stack<Character> stack = new Stack<>();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
stack.push(s.charAt(i));
}
while (!stack.empty()) {
sb.append(stack.pop());
}
return sb.toString();
}
Since the below method (using XOR) to reverse a string is not listed, I am attaching this method to reverse a string.
The Algorithm is based on :
1.(A XOR B) XOR B = A
2.(A XOR B) XOR A = B
Code snippet:
public class ReverseUsingXOR {
public static void main(String[] args) {
String str = "prateek";
reverseUsingXOR(str.toCharArray());
}
/*Example:
* str= prateek;
* str[low]=p;
* str[high]=k;
* str[low]=p^k;
* str[high]=(p^k)^k =p;
* str[low]=(p^k)^p=k;
*
* */
public static void reverseUsingXOR(char[] str) {
int low = 0;
int high = str.length - 1;
while (low < high) {
str[low] = (char) (str[low] ^ str[high]);
str[high] = (char) (str[low] ^ str[high]);
str[low] = (char) (str[low] ^ str[high]);
low++;
high--;
}
//display reversed string
for (int i = 0; i < str.length; i++) {
System.out.print(str[i]);
}
}
}
Output:
keetarp
As others have pointed out the preferred way is to use:
new StringBuilder(hi).reverse().toString()
But if you want to implement this by yourself, I'm afraid that the rest of responses have flaws.
The reason is that String represents a list of Unicode points, encoded in a char[] array according to the variable-length encoding: UTF-16.
This means some code points use a single element of the array (one code unit) but others use two of them, so there might be pairs of characters that must be treated as a single unit (consecutive "high" and "low" surrogates).
public static String reverseString(String s) {
char[] chars = new char[s.length()];
boolean twoCharCodepoint = false;
for (int i = 0; i < s.length(); i++) {
chars[s.length() - 1 - i] = s.charAt(i);
if (twoCharCodepoint) {
swap(chars, s.length() - 1 - i, s.length() - i);
}
twoCharCodepoint = !Character.isBmpCodePoint(s.codePointAt(i));
}
return new String(chars);
}
private static void swap(char[] array, int i, int j) {
char temp = array[i];
array[i] = array[j];
array[j] = temp;
}
public static void main(String[] args) throws Exception {
FileOutputStream fos = new FileOutputStream("C:/temp/reverse-string.txt");
StringBuilder sb = new StringBuilder("Linear B Syllable B008 A: ");
sb.appendCodePoint(65536); //http://unicode-table.com/es/#10000
sb.append(".");
fos.write(sb.toString().getBytes("UTF-16"));
fos.write("\n".getBytes("UTF-16"));
fos.write(reverseString(sb.toString()).getBytes("UTF-16"));
}
Using charAt() method
String name = "gaurav";
String reversedString = "";
for(int i = name.length()-1; i>=0; i--){
reversedString = reversedString + name.charAt(i);
}
System.out.println(reversedString);
Using toCharArray() method
String name = "gaurav";
char [] stringCharArray = name.toCharArray();
String reversedString = "";
for(int i = stringCharArray.length-1; i>=0; i--) {
reversedString = reversedString + stringCharArray[i];
}
System.out.println(reversedString);
Using reverse() method of the Stringbuilder
String name = "gaurav";
String reversedString = new StringBuilder(name).reverse().toString();
System.out.println(reversedString);
Check https://coderolls.com/reverse-a-string-in-java/
It is very simple in minimum code of lines
public class ReverseString {
public static void main(String[] args) {
String s1 = "neelendra";
for(int i=s1.length()-1;i>=0;i--)
{
System.out.print(s1.charAt(i));
}
}
}
This did the trick for me
public static void main(String[] args) {
String text = "abcdefghijklmnopqrstuvwxyz";
for (int i = (text.length() - 1); i >= 0; i--) {
System.out.print(text.charAt(i));
}
}
1. Using Character Array:
public String reverseString(String inputString) {
char[] inputStringArray = inputString.toCharArray();
String reverseString = "";
for (int i = inputStringArray.length - 1; i >= 0; i--) {
reverseString += inputStringArray[i];
}
return reverseString;
}
2. Using StringBuilder:
public String reverseString(String inputString) {
StringBuilder stringBuilder = new StringBuilder(inputString);
stringBuilder = stringBuilder.reverse();
return stringBuilder.toString();
}
OR
return new StringBuilder(inputString).reverse().toString();
System.out.print("Please enter your name: ");
String name = keyboard.nextLine();
String reverse = new StringBuffer(name).reverse().toString();
String rev = reverse.toLowerCase();
System.out.println(rev);
I used this method to turn names backwards and into lower case.
One natural way to reverse a String is to use a StringTokenizer and a stack. Stack is a class that implements an easy-to-use last-in, first-out (LIFO) stack of objects.
String s = "Hello My name is Sufiyan";
Put it in the stack frontwards
Stack<String> myStack = new Stack<>();
StringTokenizer st = new StringTokenizer(s);
while (st.hasMoreTokens()) {
myStack.push(st.nextToken());
}
Print the stack backwards
System.out.print('"' + s + '"' + " backwards by word is:\n\t\"");
while (!myStack.empty()) {
System.out.print(myStack.pop());
System.out.print(' ');
}
System.out.println('"');
public String reverse(String s) {
String reversedString = "";
for(int i=s.length(); i>0; i--) {
reversedString += s.charAt(i-1);
}
return reversedString;
}
public class Test {
public static void main(String args[]) {
StringBuffer buffer = new StringBuffer("Game Plan");
buffer.reverse();
System.out.println(buffer);
}
}
All above solution is too good but here I am making reverse string using recursive programming.
This is helpful for who is looking recursive way of doing reverse string.
public class ReversString {
public static void main(String args[]) {
char s[] = "Dhiral Pandya".toCharArray();
String r = new String(reverse(0, s));
System.out.println(r);
}
public static char[] reverse(int i, char source[]) {
if (source.length / 2 == i) {
return source;
}
char t = source[i];
source[i] = source[source.length - 1 - i];
source[source.length - 1 - i] = t;
i++;
return reverse(i, source);
}
}
You can also try this:
public class StringReverse {
public static void main(String[] args) {
String str = "Dogs hates cats";
StringBuffer sb = new StringBuffer(str);
System.out.println(sb.reverse());
}
}
Procedure :
We can use split() to split the string .Then use reverse loop and add the characters.
Code snippet:
class test
{
public static void main(String args[])
{
String str = "world";
String[] split= str.split("");
String revers = "";
for (int i = split.length-1; i>=0; i--)
{
revers += split[i];
}
System.out.printf("%s", revers);
}
}
//output : dlrow
It gets the value you typed and returns it reversed ;)
public static String reverse (String a){
char[] rarray = a.toCharArray();
String finalvalue = "";
for (int i = 0; i < rarray.length; i++)
{
finalvalue += rarray[rarray.length - 1 - i];
}
return finalvalue;
}
public String reverseWords(String s) {
String reversedWords = "";
if(s.length()<=0) {
return reversedWords;
}else if(s.length() == 1){
if(s == " "){
return "";
}
return s;
}
char arr[] = s.toCharArray();
int j = arr.length-1;
while(j >= 0 ){
if( arr[j] == ' '){
reversedWords+=arr[j];
}else{
String temp="";
while(j>=0 && arr[j] != ' '){
temp+=arr[j];
j--;
}
j++;
temp = reverseWord(temp);
reversedWords+=temp;
}
j--;
}
String[] chk = reversedWords.split(" ");
if(chk == null || chk.length == 0){
return "";
}
return reversedWords;
}
public String reverseWord(String s){
char[] arr = s.toCharArray();
for(int i=0,j=arr.length-1;i<=j;i++,j--){
char tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
return String.valueOf(arr);
}
public static void main(String[] args) {
String str = "Prashant";
int len = str.length();
char[] c = new char[len];
for (int j = len - 1, i = 0; j >= 0; j--, i++) {
c[i] = str.charAt(j);
}
str = String.copyValueOf(c);
System.out.println(str);
}
public void reverString(){
System.out.println("Enter value");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
try{
String str=br.readLine();
char[] charArray=str.toCharArray();
for(int i=charArray.length-1; i>=0; i--){
System.out.println(charArray[i]);
}
}
catch(IOException ex){
}
recursion:
public String stringReverse(String string) {
if (string == null || string.length() == 0) {
return string;
}
return stringReverse(string.substring(1)) + string.charAt(0);
}
Sequence of characters (or) StringString's Family:
String testString = "Yashwanth#777"; // ~1 1⁄4→D800₁₆«2²⁰
Using Java 8 Stream API
First we convert String into stream by using method CharSequence.chars(), then we use the method IntStream.range to generate a sequential stream of numbers. Then we map this sequence of stream into String.
public static String reverseString_Stream(String str) {
IntStream cahrStream = str.chars();
final int[] array = cahrStream.map( x -> x ).toArray();
int from = 0, upTo = array.length;
IntFunction<String> reverseMapper = (i) -> ( Character.toString((char) array[ (upTo - i) + (from - 1) ]) );
String reverseString = IntStream.range(from, upTo) // for (int i = from; i < upTo ; i++) { ... }
.mapToObj( reverseMapper ) // array[ lastElement ]
.collect(Collectors.joining()) // Joining stream of elements together into a String.
.toString(); // This object (which is already a string!) is itself returned.
System.out.println("Reverse Stream as String : "+ reverseString);
return reverseString;
}
Using a Traditional for Loop
If you want to reverse the string then we need to follow these steps.
Convert String into an Array of Characters.
Iterate over an array in reverse order, append each Character to temporary string variable until the last character.
public static String reverseString( String reverse ) {
if( reverse != null && reverse != "" && reverse.length() > 0 ) {
char[] arr = reverse.toCharArray();
String temp = "";
for( int i = arr.length-1; i >= 0; i-- ) {
temp += arr[i];
}
System.out.println("Reverse String : "+ temp);
}
return null;
}
Easy way to Use reverse method provided form StringBuffer or StringBuilder Classes
StringBuilder and StringBuffer are mutable sequence of characters. That means one can change the value of these object's.
StringBuffer buffer = new StringBuffer(str);
System.out.println("StringBuffer - reverse : "+ buffer.reverse() );
String builderString = (new StringBuilder(str)).reverse().toString;
System.out.println("StringBuilder generated reverse String : "+ builderString );
StringBuffer has the same methods as the StringBuilder, but each method in StringBuffer is synchronized so it is thread safe.
public static String revString(String str){
char[] revCharArr = str.toCharArray();
for (int i=0; i< str.length()/2; i++){
char f = revCharArr[i];
char l = revCharArr[str.length()-i-1];
revCharArr[i] = l;
revCharArr[str.length()-i-1] = f;
}
String revStr = new String(revCharArr);
return revStr;
}
Simple For loop in java
public void reverseString(char[] s) {
int length = s.length;
for (int i = 0; i < s.length / 2; i++) {
// swaping character
char temp = s[length - i - 1];
s[length - i - 1] = s[i];
s[i] = temp;
}
}

How to remove duplicate character from a string in java?

In my program, the user enters a string, and it first finds the largest mode of characters in the string. Next, my program is supposed to remove all duplicates of a character in a string, (user input: aabc, program prints: abc) which I'm not entirely certain on how to do. I can get it to remove duplicates from some strings, but not all. For example, when the user puts "aabc" it will print "abc", but if the user puts "aabbhh", it will print "abbhh." Also, before I added the removeDup method to my program, it would only print the maxMode once, but after I added the removeDup method, it began to print the maxMode twice. How do I keep it from printing it twice?
Note: I cannot convert the strings to an array.
import java.util.Scanner;
public class JavaApplication3 {
static class MyStrings {
String s;
void setMyStrings(String str) {
s = str;
}
int getMode() {
int i;
int j;
int count = 0;
int maxMode = 0, maxCount = 1;
for (i = 0; i< s.length(); i++) {
maxCount = count;
count = 0;
for (j = s.length()-1; j >= 0; j--) {
if (s.charAt(j) == s.charAt(i))
count++;
if (count > maxCount){
maxCount = count;
maxMode = i;
}
}
}
System.out.println(s.charAt(maxMode)+" = largest mode");
return maxMode;
}
String removeDup() {
getMode();
int i;
int j;
String rdup = "";
for (i = 0; i< s.length(); i++) {
int count = 1;
for (j = 0; j < rdup.length(); j++) {
if (s.charAt(i) == s.charAt(j)){
count++;
}
}
if (count == 1){
rdup += s.charAt(i);
}
}
System.out.print(rdup);
System.out.println();
return rdup;
}
}
public static void main (String[] args) {
Scanner in = new Scanner(System.in);
MyStrings setS = new MyStrings();
String s;
System.out.print("Enter string:");
s = in.nextLine();
setS.setMyStrings(s);
setS.getMode();
setS.removeDup();
}
}
Try this method...should work fine!
String removeDup()
{
getMode();
int i;
int j;
String rdup = "";
for (i = 0; i< s.length(); i++) {
int count = 1;
for (j = i+1; j < s.length(); j++) {
if (s.charAt(i) == s.charAt(j)) {
count++;
}
}
if (count == 1){
rdup += s.charAt(i);
}
}
// System.out.print(rdup);
System.out.println();
return rdup;
}
Welcome to StackOverflow!
You're calling getMode() both outside and inside of removeDup(), which is why it's printing it twice.
In order to remove all duplicates, you'll have to call removeDup() over and over until all the duplicates are gone from your string. Right now you're only calling it once.
How might you do that? Think about how you're detecting duplicates, and use that as the end condition for a while loop or similar.
Happy coding!
Shouldn't this be an easier way? Also, i'm still learning.
import java.util.*;
public class First {
public static void main(String arg[])
{
Scanner sc= new Scanner(System.in);
StringBuilder s=new StringBuilder(sc.nextLine());
//String s=new String();
for(int i=0;i<s.length();i++){
String a=s.substring(i, i+1);
while(s.indexOf(a)!=s.lastIndexOf(a)){s.deleteCharAt(s.lastIndexOf(a));}
}
System.out.println(s.toString());
}
}
You can do this:
public static void main(String[] args) {
String str = new String("PINEAPPLE");
Set <Character> letters = new <Character>HashSet();
for (int i = 0; i < str.length(); i++) {
letters.add(str.charAt(i));
}
System.out.println(letters);
}
I think an optimized version which supports ASCII codes can be like this:
public static void main(String[] args) {
System.out.println(removeDups("*PqQpa abbBBaaAAzzK zUyz112235KKIIppP!!QpP^^*Www5W38".toCharArray()));
}
public static String removeDups(char []input){
long ocr1=0l,ocr2=0l,ocr3=0;
int index=0;
for(int i=0;i<input.length;i++){
int val=input[i]-(char)0;
long ocr=val<126?val<63?ocr1:ocr2:ocr3;
if((ocr& (1l<<val))==0){//not duplicate
input[index]=input[i];
index++;
}
if(val<63)
ocr1|=(1l<<val);
else if(val<126)
ocr2|=(1l<<val);
else
ocr3|=(1l<<val);
}
return new String(input,0,index);
}
please keep in mind that each of orc(s) represent a mapping of a range of ASCII characters and each java long variable can grow as big as (2^63) and since we have 128 characters in ASCII so we need three ocr(s) which basically maps the occurrences of the character to a long number.
ocr1: (char)0 to (char)62
ocr2: (char)63 to (char)125
ocr3: (char)126 to (char)128
Now if a duplicate was found the
(ocr& (1l<<val))
will be greater than zero and we skip that char and finally we can create a new string with the size of index which shows last non duplicate items index.
You can define more orc(s) and support other character-sets if you want.
Can use HashSet as well as normal for loops:
public class RemoveDupliBuffer
{
public static String checkDuplicateNoHash(String myStr)
{
if(myStr == null)
return null;
if(myStr.length() <= 1)
return myStr;
char[] myStrChar = myStr.toCharArray();
HashSet myHash = new HashSet(myStrChar.length);
myStr = "";
for(int i=0; i < myStrChar.length ; i++)
{
if(! myHash.add(myStrChar[i]))
{
}else{
myStr += myStrChar[i];
}
}
return myStr;
}
public static String checkDuplicateNo(String myStr)
{
// null check
if (myStr == null)
return null;
if (myStr.length() <= 1)
return myStr;
char[] myChar = myStr.toCharArray();
myStr = "";
int tail = 0;
int j = 0;
for (int i = 0; i < myChar.length; i++)
{
for (j = 0; j < tail; j++)
{
if (myChar[i] == myChar[j])
{
break;
}
}
if (j == tail)
{
myStr += myChar[i];
tail++;
}
}
return myStr;
}
public static void main(String[] args) {
String myStr = "This is your String";
myStr = checkDuplicateNo(myStr);
System.out.println(myStr);
}
Try this simple answer- works well for simple character string accepted as user input:
import java.util.Scanner;
public class string_duplicate_char {
String final_string = "";
public void inputString() {
//accept string input from user
Scanner user_input = new Scanner(System.in);
System.out.println("Enter a String to remove duplicate Characters : \t");
String input = user_input.next();
user_input.close();
//convert string to char array
char[] StringArray = input.toCharArray();
int StringArray_length = StringArray.length;
if (StringArray_length < 2) {
System.out.println("\nThe string with no duplicates is: "
+ StringArray[1] + "\n");
} else {
//iterate over all elements in the array
for (int i = 0; i < StringArray_length; i++) {
for (int j = i + 1; j < StringArray_length; j++) {
if (StringArray[i] == StringArray[j]) {
int temp = j;//set duplicate element index
//delete the duplicate element by copying the adjacent elements by one place
for (int k = temp; k < StringArray_length - 1; k++) {
StringArray[k] = StringArray[k + 1];
}
j++;
StringArray_length--;//reduce char array length
}
}
}
}
System.out.println("\nThe string with no duplicates is: \t");
//print the resultant string with no duplicates
for (int x = 0; x < StringArray_length; x++) {
String temp= new StringBuilder().append(StringArray[x]).toString();
final_string=final_string+temp;
}
System.out.println(final_string);
}
public static void main(String args[]) {
string_duplicate_char object = new string_duplicate_char();
object.inputString();
}
}
Another easy solution to clip the duplicate elements in a string using HashSet and ArrayList :
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Scanner;
public class sample_work {
public static void main(String args[]) {
String input = "";
System.out.println("Enter string to remove duplicates: \t");
Scanner in = new Scanner(System.in);
input = in.next();
in.close();
ArrayList<Character> String_array = new ArrayList<Character>();
for (char element : input.toCharArray()) {
String_array.add(element);
}
HashSet<Character> charset = new HashSet<Character>();
int array_len = String_array.size();
System.out.println("\nLength of array = " + array_len);
if (String_array != null && array_len > 0) {
Iterator<Character> itr = String_array.iterator();
while (itr.hasNext()) {
Character c = (Character) itr.next();
if (charset.add(c)) {
} else {
itr.remove();
array_len--;
}
}
}
System.out.println("\nThe new string with no duplicates: \t");
for (int i = 0; i < array_len; i++) {
System.out.println(String_array.get(i).toString());
}
}
}
your can use this simple code and understand how to remove duplicates values from string.I think this is the simplest way to understand this problem.
class RemoveDup
{
static int l;
public String dup(String str)
{
l=str.length();
System.out.println("length"+l);
char[] c=str.toCharArray();
for(int i=0;i<l;i++)
{
for(int j=0;j<l;j++)
{
if(i!=j)
{
if(c[i]==c[j])
{
l--;
for(int k=j;k<l;k++)
{
c[k]=c[k+1];
}
j--;
}
}
}
}
System.out.println("after concatination lenght:"+l);
StringBuilder sd=new StringBuilder();
for(int i=0;i<l;i++)
{
sd.append(c[i]);
}
str=sd.toString();
return str;
}
public static void main(String[] ar)
{
RemoveDup obj=new RemoveDup();
Scanner sc=new Scanner(System.in);
String st,t;
System.out.println("enter name:");
st=sc.nextLine();
sc.close();
t=obj.dup(st);
System.out.println(t);
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication26;
import java.util.*;
/**
*
* #author THENNARASU
*/
public class JavaApplication26 {
public static void main(String[] args) {
int i,j,k=0,count=0,m;
char a[]=new char[10];
char b[]=new char[10];
Scanner ob=new Scanner(System.in);
String str;
str=ob.next();
a=str.toCharArray();
int c=str.length();
for(j=0;j<c;j++)
{
for(i=0;i<j;i++)
{
if(a[i]==a[j])
{
count=1;
}
}
if(count==0)
{
b[k++]=a[i];
}
count=0;
}
for(m=0;b[m]!='\0';m++)
{
System.out.println(b[m]);
}
}
}
i wrote this program. Am using 2 char arrays instead. You can define the number of duplicate chars you want to eliminate from the original string and also shows the number of occurances of each character in the string.
public String removeMultipleOcuranceOfChar(String string, int numberOfChars){
char[] word1 = string.toCharArray();
char[] word2 = string.toCharArray();
int count=0;
StringBuilder builderNoDups = new StringBuilder();
StringBuilder builderDups = new StringBuilder();
for(char x: word1){
for(char y : word2){
if (x==y){
count++;
}//end if
}//end inner loop
System.out.println(x + " occurance: " + count );
if (count ==numberOfChars){
builderNoDups.append(x);
}else{
builderDups.append(x);
}//end if else
count = 0;
}//end outer loop
return String.format("Number of identical chars to be in or out of input string: "
+ "%d\nOriginal word: %s\nWith only %d identical chars: %s\n"
+ "without %d identical chars: %s",
numberOfChars,string,numberOfChars, builderNoDups.toString(),numberOfChars,builderDups.toString());
}
Try this simple solution for REMOVING DUPLICATE CHARACTERS/LETTERS FROM GIVEN STRING
import java.util.Scanner;
public class RemoveDuplicateLetters {
public static void main(String[] args) {
Scanner scn=new Scanner(System.in);
System.out.println("enter a String:");
String s=scn.nextLine();
String ans="";
while(s.length()>0)
{
char ch = s.charAt(0);
ans+= ch;
s = s.replace(ch+"",""); //Replacing all occurrence of the current character by a spaces
}
System.out.println("after removing all duplicate letters:"+ans);
}
}
In Java 8 we can do that using
private void removeduplicatecharactersfromstring() {
String myString = "aabcd eeffff ghjkjkl";
StringBuilder builder = new StringBuilder();
Arrays.asList(myString.split(" "))
.forEach(s -> {
builder.append(Stream.of(s.split(""))
.distinct().collect(Collectors.joining()).concat(" "));
});
System.out.println(builder); // abcd ef ghjkl
}

Categories