How to reverse a string - java

I need to reverse the string of a user's input.
I need it done in the simplest of ways. I was trying to do reverseOrder(UserInput) but it wasn't working.
For example, user inputs abc I just take the string and print out cba

new StringBuilder(str).reverse().toString()
java.util.Collections.reverseOrder is for sorting in reverse of normal order.

I prefer using Apache's commons-lang for this kind of thing. There are all kinds of goodies, including:
StringUtils.reverse("Hello World!");
yields: !dlroW olleH
StringUtils.reverseDelimited("Hello World!", ' ');
yields: World! Hello

If you are new to programming, which I guess you are, my suggestion is "Why use simple stuff?".
Understand the internals and play some!!
public static void main(String[] args) {
String str = "abcasz";
char[] orgArr = str.toCharArray();
char[] revArr = new char[orgArr.length];
for (int i = 0; i < orgArr.length;i++) {
revArr[i] = orgArr[orgArr.length - 1 - i];
}
String revStr = new String(revArr);
System.out.println(revStr);

There is an interesting method to do it so too.
String input = "abc";
//Here, input is String to reverse
int b = input.length();
String reverse = ""; // Declaring reverse String variable
while(b!=0){
//Loop for switching between the characters of the String input
reverse += (input.charAt(b-1));
b--;
}
System.out.println(reverse);

public String reverseString(final String input_String)
{
char temp;
char[] chars = input_String.toCharArray();
int N = chars.length;
for (int i = 0 ; i < (N / 2) ; i++)
{
temp = chars[i];
chars[i] = chars[N - 1 - i];
chars[N - 1 - i] = temp;
}
return new String(chars);
}
Run :
Pandora
arodnaP

Without going through the char sequence, easiest way:
public String reverse(String post) {
String backward = "";
for(int i = post.length() - 1; i >= 0; i--) {
backward = backward + post.substring(i, i + 1);
}
return backward;
}

Related

How can I move multiple character arrays to the back of an array based upon a specific index?

I have a string "Hello, World!" that I have to convert into a char array. I then found the index of the char ',' - to which I want to create a new char array that contains " World!, Hello".
I've got the first index of the char array moved to the back - such that it prints out "ello, World!H".
How can I use my variable indexDelimiter to move the rest of the char arrays (as well as the ',') to the back? I've been looking at this problem forever, and I'm very confused as to how I could go about this.
I can't use ListArray. I has to be an Array.
public class ArrayTest {
public static void main(String[] args) {
String s = "Hello, World!";
char[] oldCharArray = s.toCharArray();
char[] newCharArray = new char[oldCharArray.length];
char delimiter = ',';
int indexDelimiter = new String(oldCharArray).indexOf(delimiter);
for (int i = 0; i < oldCharArray.length - 1; i++) {
newCharArray[i] = oldCharArray[i + 1];
}
newCharArray[oldCharArray.length - 1] = oldCharArray[0];
for (int i = 0; i < newCharArray.length; i++) {
System.out.print(newCharArray[i]);
}
// This prints out "ello, World!H" but I want " World!, Hello"
}
}
This code will produce "World!,Hello", take a look and see if it meets your needs.
public static void main(String args[]) {
String s = "Hello, World!";
char[] oldCharArray = s.toCharArray();
char[] newCharArray = new char[oldCharArray.length];
char delimiter = ',';
int indexDelimiter = new String(oldCharArray).indexOf(delimiter);
int i = 0;
for (i = 0; i < oldCharArray.length-indexDelimiter-1; i++) {
newCharArray[i] = oldCharArray[indexDelimiter + i + 1];
}
newCharArray[i] = delimiter;
i++;
int j = i;
while (i < oldCharArray.length) {
newCharArray[i] = oldCharArray[i - j];
i++;
}
System.out.println(newCharArray);
}
If you mean backward, you can reverse the by splitting it first
public char[] reverse_comma_split(String str) {
String[] spl = str.split(",");
String reversed = new String();
for (int i = spl.length - 1; i >= 0; i--) {
reversed += spl[i];
if (i != 0)
reversed += ", ";
}
return reversed.toCharArray();
}
Calling reverse_comma_split("Hello, world!") would return a char array of " world!, Hello"
However, if you insist to get uppercase char in every split, you can modify the loop in which spl[i] to spl[i].substring(0, 1).toUpperCase() + spl[i].substring(1)

Reverse String characters in java

Am trying to reverse a string using a method in java, I can fetch all the elements of the string and print them out in order via a loop, my problem is reversing the string such that the first comes last and the last comes first, I tried to find a reverse function to no avail... Here is what I have so far...
private static void palindrome() {
char[] name = new char[]{};
String name1;
System.out.println("Enter your name");
Scanner tim = new Scanner(System.in);
name1 = tim.next();
int len = name1.length();
for (int i = 0; i <= len; ++i) {
char b = name1.charAt(i);
System.out.println(b + " ");
}
}
That loop succeeds in printing out the single characters from the string.
You can use StringBuilder like this:
import java.lang.*;
import java.io.*;
import java.util.*;
class ReverseString {
public static void main(String[] args) {
String input = "Geeks for Geeks";
StringBuilder input1 = new StringBuilder();
// append a string into StringBuilder input1
input1.append(input);
// reverse StringBuilder input1
input1 = input1.reverse();
// print reversed String
System.out.println(input1);
}
}
You can also modify your code to do this:
1 -
for (int i = 0; i <= len; ++i) {
char b = name1[len - i];
System.out.println(b + " ");
}
2 -
for (int i = len; i >= 0; --i) {
char b = name1.charAt(i);
System.out.println(b + " ");
}
Using Java 9 codePoints stream you can reverse a string as follows. This example shows the reversal of a string containing surrogate pairs. It works with regular characters as well.
String str = "𝕙𝕖𝕝𝕝𝕠 𝕨𝕠𝕣𝕝𝕕";
String reversed = str.codePoints()
// Stream<String>
.mapToObj(Character::toString)
// concatenate in reverse order
.reduce((a, b) -> b + a)
.get();
System.out.println(reversed); // 𝕕𝕝𝕣𝕠𝕨 𝕠𝕝𝕝𝕖𝕙
See also: Reverse string printing method
You simply need to loop through the array backwards:
for (int i = len - 1; i >= 0; i--) {
char b = name1.charAt(i);
System.out.println(b + " ");
}
You start at the last element which has its index at the position length - 1 and iterate down to the first element (with index zero).
This concept is not specific to Java and also applies to other data structures that provide index based access (such as lists).
Use the built-in reverse() method of the StringBuilder class.
private static void palindrome() {
String name1;
StringBuilder input = new StringBuilder();
System.out.println("Enter your name");
Scanner tim = new Scanner(System.in);
name1 = tim.next();
input.append(name1);
input.reverse();
System.out.println(input);
}
Added reverse() function for your understanding
import java.util.Scanner;
public class P3 {
public static void main(String[] args) {
palindrome();
}
private static void palindrome() {
char[] name = new char[]{};
String name1;
System.out.println("Enter your name");
Scanner tim = new Scanner(System.in);
name1 = tim.next();
String nameReversed = reverse(name1);
int len = name1.length();
for (int i = 0; i < len; ++i) {
char b = name1.charAt(i);
System.out.println(b + " ");
}
}
private static String reverse(String name1) {
char[] arr = name1.toCharArray();
int left = 0, right = arr.length - 1;
while (left < right) {
//swap characters first and last positions
char temp = arr[left];
arr[left++] = arr[right];
arr[right--] = temp;
}
return new String(arr);
}
}
you can try the build-in function charAt()
private String reverseString2(String str) {
if (str == null) {
return null;
}
String result = "";
for (int i = str.length() - 1; i >= 0; i--) {
result = result + str.charAt(i);
}
return result;
}
public void test(){
System.out.println(reverseString2("abcd"));
}
see also rever a string in java
String reversed = new StringBuilder(originalString).reverse().toString();

Print String words reverse - edge cases

I try to create a function that changes the String from StackOverflow is the best. to best. the is StackOverflow.
I wrote the following function, but can't seem to fix the spaces in the result string. For some reason, I receive best.the is Stackoverflow. There is no space between best. & the, and there is an extra space after StackOverflow.
I could add a variable that represents space and use if's in the edge cases, but I believe that there is a better way to do so.
Could anyone help me figure this out?
public static void main(String[] args) {
String str = "Stackoverflow is the best.";
String result = change(str);
System.out.println(result);
}
private static String change(String str) {
String result = "";
int i1 = str.length()-1;
int i2 = str.length();
for (i1 = str.length(); i1 >= 0; i1--) {
if (i1 ==0 || str.charAt(i1-1) == ' ') {
result = result.concat(str.substring(i1, i2));
i2 = i1;
}
}
return result;
}
One way i could think of without using if's is :
String line = "Stackoverflow is the best.";
String delimeter = " ";
final String[] words = line.split(delimeter);
String reversedLine = "";
for(int i = words.length - 1; i >= 0; i--) {
reversedLine += words[i] + delimeter;
}
// remove the delimeter present at last of line
reversedLine = reversedLine.substring(0, reversedLine.length() - 1);
System.out.println(reversedLine);
To generate the output as you have mentioned, I would approach a problem in this way:
class Solution {
public static void main(String[] args) {
String str = "StackOverflow is the best.";
String[] arr = str.split(" ");
System.out.print(arr[arr.length-1]);
for(int i = arr.length - 2; i >= 0; i--){
System.out.print(" "+arr[i]);
}
}
}
The only reason to your problem is that you haven't added the space after the '.'
Try using String str = "Stackoverflow is the best. ";
Hope it helped... :)

How to split a string after 2nd occurrence of dot(.) in java

I have a string which looks something like this(the most basic form):
String str = "1.0.0.190"
The str can be something like this as well:
1.11.0.12 or 2.111.1.190 or 1.0.0.0
I want to split the string at the 2nd occurrence of the dot(.). How can I achieve that ?
Output:
String str = "1.0.0.190"
String output = "1.0"
I'd fit the answer to OP's level, so I wouldn't recommend split or regexps to him...
If you need substring to second dot, simply find second dot and cut the string to that position...
public class DotSubstring {
public static void main(String[] args) {
String s = "1.2.3.4";
int secondDotPosition = findSecondDotPosition(s);
if (secondDotPosition > 0) {
System.out.println(s.substring(0, secondDotPosition));
} else {
System.out.printf("ERROR: there is not a 2nd dot in '%s'%n", s);
}
}
private static int findSecondDotPosition(String s) {
int result = -1;
int dotsToFind = 2;
char[] ca = s.toCharArray();
for (int i = 0; i < ca.length; ++i) {
if (ca[i] == '.') --dotsToFind;
if (dotsToFind == 0) return i;
}
return result;
}
}
The problem with split for beginner is, that is accepts regexp, that's why it is escaped in Joop Eggen's answe like this str.split("\\.").
And yes, that can be achieved in one line as user3458271 wrote in a comment same as xyz later in answer, just error checking would be more difficult (for example if there are no 2 dots...).
In one line with substring and indexOf:
String output = str.substring(0,str.indexOf(".",str.indexOf(".")+1));
public static void main(String[] args) {
String input = "2.111.1.190";
String[] out = input.split("\\.");
String output1 = out[0]+"."+out[1];
System.out.println(output1);
String output2 = "";
for(int x=2; x < out.length; x++)
output2 += out[x] +".";
System.out.println(output2);
}
For the other fields too:
String[] halfs = str.split("\\.");
String[] fulls = new String[halfs.length / 2];
for (int i = 0; i < fulls.length; ++i) {
fulls[i] = halfs[2*i] + "." + halfs[2*i + 1];
}
return fulls[0];
The same technique reduced for the first field:
String[] halfs = str.split("\\.", 3);
return halfs[0] + "." + halfs[1];
Simply:
return str.replaceAll("^([^.]*\\.[^.]*)\\..*$", "$1");

Java: String - add character n-times [duplicate]

This question already has answers here:
Simple way to repeat a string
(32 answers)
Closed 4 years ago.
Is there a simple way to add a character or another String n-times to an existing String?
I couldn’t find anything in String, Stringbuilder, etc.
Apache commons-lang3 has StringUtils.repeat(String, int), with this one you can do (for simplicity, not with StringBuilder):
String original;
original = original + StringUtils.repeat("x", n);
Since it is open source, you can read how it is written. There is a minor optimalization for small n-s if I remember correctly, but most of the time it uses StringBuilder.
In case of Java 8 you can do:
int n = 4;
String existing = "...";
String result = existing + String.join("", Collections.nCopies(n, "*"));
Output:
...****
In Java 8 the String.join method was added. But Collections.nCopies is even in Java 5.
You are able to do this using Java 8 stream APIs. The following code creates the string "cccc" from "c":
String s = "c";
int n = 4;
String sRepeated = IntStream.range(0, n).mapToObj(i -> s).collect(Collectors.joining(""));
For the case of repeating a single character (not a String), you could use Arrays.fill:
String original = "original ";
char c = 'c';
int number = 9;
char[] repeat = new char[number];
Arrays.fill(repeat, c);
original += new String(repeat);
Use this:
String input = "original";
String newStr = "new"; //new string to be added
int n = 10 // no of times we want to add
input = input + new String(new char[n]).replace("\0", newStr);
You can use Guava's Strings.repeat method:
String existingString = ...
existingString += Strings.repeat("foo", n);
for(int i = 0; i < n; i++) {
existing_string += 'c';
}
but you should use StringBuilder instead, and save memory
int n = 3;
String existing_string = "string";
StringBuilder builder = new StringBuilder(existing_string);
for (int i = 0; i < n; i++) {
builder.append(" append ");
}
System.out.println(builder.toString());
Its better to use StringBuilder instead of String because String is an immutable class and it cannot be modified once created: in String each concatenation results in creating a new instance of the String class with the modified string.
In addition to the answers above, you should initialize the StringBuilder with an appropriate capacity, especially that you already know it. For example:
int capacity = existingString.length() + n * appendableString.length();
StringBuilder builder = new StringBuilder(capacity);
public String appendNewStringToExisting(String exisitingString, String newString, int number) {
StringBuilder builder = new StringBuilder(exisitingString);
for(int iDx = 0; iDx < number; iDx++){
builder.append(newString);
}
return builder.toString();
}
String toAdd = "toAdd";
StringBuilder s = new StringBuilder();
for(int count = 0; count < MAX; count++) {
s.append(toAdd);
}
String output = s.toString();
Keep in mind that if the "n" is large, it might not be such a great idea to use +=, since every time you add another String through +=, the JVM will create a brand new object (plenty of info on this around).
Something like:
StringBuilder b = new StringBuilder(existing_string);
for(int i = 0; i<n; i++){
b.append("other_string");
}
return b.toString();
Not actually coding this in an IDE, so minor flaws may occur, but this is the basic idea.
How I did it:
final int numberOfSpaces = 22;
final char[] spaceArray = new char[numberOfSpaces];
Arrays.fill(spaces, ' ');
Now add it to your StringBuilder
stringBuilder.append(spaceArray);
or String
final String spaces = String.valueOf(spaceArray);
To have an idea of the speed penalty, I have tested two versions, one with Array.fill and one with StringBuilder.
public static String repeat(char what, int howmany) {
char[] chars = new char[howmany];
Arrays.fill(chars, what);
return new String(chars);
}
and
public static String repeatSB(char what, int howmany) {
StringBuilder out = new StringBuilder(howmany);
for (int i = 0; i < howmany; i++)
out.append(what);
return out.toString();
}
using
public static void main(String... args) {
String res;
long time;
for (int j = 0; j < 1000; j++) {
res = repeat(' ', 100000);
res = repeatSB(' ', 100000);
}
time = System.nanoTime();
res = repeat(' ', 100000);
time = System.nanoTime() - time;
System.out.println("elapsed repeat: " + time);
time = System.nanoTime();
res = repeatSB(' ', 100000);
time = System.nanoTime() - time;
System.out.println("elapsed repeatSB: " + time);
}
(note the loop in main function is to kick in JIT)
The results are as follows:
elapsed repeat: 65899
elapsed repeatSB: 305171
It is a huge difference
Here is a simple way..
for(int i=0;i<n;i++)
{
yourString = yourString + "what you want to append continiously";
}

Categories