String newStr;
public RandomCuriosity(String input){
newStr = input;
}
public void shiftChars(){
char[] oldChar = newStr.toCharArray();
char[] newChar = new char[oldChar.length];
newChar[0] = oldChar[oldChar.length-1];
for(int i = 1; i < oldChar.length; i++){
newChar[i] = oldChar[i-1];
}
newStr = String.valueOf(newChar);
}
I created a method that shifts characters forward by one. For example, the input could be:
The input: Stackoverflow
The output: wStackoverflo
How I did it is I mutated an instance of a string. Convert that string to a char array (calling it oldChar), assigned the last index of of oldChar as the first index of newChar, and made a for-loop that took the first index of oldChar as the second index of my new Char array and so forth. Lastly, I converted the char array back to a string.
I feel like I did way too much to do something very simple. Is there a more efficient way to do something like this?
EDIT Thanks for the great answers!
newStr = newStr.charAt(newStr.length() - 1) + newStr.substring(0, newStr.length() - 1);
You can made your life simpler :
public static void main (String[] args) throws java.lang.Exception {
String input = "Stackoverflow";
for(int i = 0; i < s.length(); i++){
input = shift(input);
System.out.println(input);
}
}
public static String shift(String s) {
return s.charAt(s.length()-1)+s.substring(0, s.length()-1);
}
Output :
wStackoverflo
owStackoverfl
lowStackoverf
flowStackover
rflowStackove
erflowStackov
verflowStacko
overflowStack
koverflowStac
ckoverflowSta
ackoverflowSt
tackoverflowS
Stackoverflow
You could use System.arrayCopy:
char[] oldChar = newStr.toCharArray();
char[] newChar = new char[oldChar.length];
newChar[0] = oldChar[oldChar.length - 1];
System.arrayCopy(oldChar, 0, newChar, 1, oldChar.length - 1);
You can use StringBuilders.
StringBuilder strb = new StringBuilder();
strb.append(oldChar[oldChar.length-1]).append(oldchar.substring(0, oldChar.length-1));
newStr = strb.toString();
try this..
String old = "String";
char first = old.charAt(old.length()-1);
String newString = first+old.substring(0,old.length()-1);
System.out.println(newString);
Another solution, but without using loops, for left and right shift:
public static String cyclicLeftShift(String s, int n){ //'n' is the number of characters to shift left
n = n%s.length();
return s.substring(n) + s.substring(0, n);
}
public static String cyclicRightShift(String s, int n){ //'n' is the number of characters to shift right
n = n%s.length();
return s.substring(s.length() - n , s.length()) + s.substring(0, s.length() - n);
}
By Java, u can shift it to forward by O(n) where n is how many times to go forward by character which space o(1)
public static String shiftChars(String s , int times) {
String temp = s;
for (int i = 0; i < times ; i++) {
temp = temp.charAt(temp.length()-1)+temp.substring(0, temp.length()-1);
}
return temp;
}
Related
I'm tying to learn Java. I need to make a method called reverse that gets a string and return a string (but in reverse order). Here is what i tried. Can you fix the code and explain what I'm doing wrong? Please also give me some advice about a good start in Java. Thank you!
public class Test{
public static String reverse(String a){
int j = a.length();
char[] newWord = new char[j];
for(int i=0;i<a.length();i++)
{
newWord[j] = a.charAt(i);
j--;
}
return new String(newWord);
}
public static void main(String a[]){
String word = "abcdefgh";
System.out.println(reverse(word));
}
}
You can use this to reverse the string, you don't need to use your own method
new StringBuilder(word).reverse().toString()
If you want to use your solution you must change int j = a.length() to int j = a.length() -1;
The fixed code is
public class Test {
public static String reverse(String a) {
int j = a.length();
char[] newWord = new char[j];
for (int i = 0; i < a.length(); i++) {
newWord[--j] = a.charAt(i);
}
return new String(newWord);
}
public static void main(String a[]) {
String word = "abcdefgh";
System.out.println(reverse(word));
}
}
Like others have mentioned, arrays indexes start at 0. So if an array has size 5 for example it has indices 0,1,2,3,4. It does not have an index 5.
For an example of a string with length 5, the code change that I did newWord[--j] = a.charAt(i); will assign to the indices 4,3,2,1,0 in that order.
Regarding getting a good start in Java, I think you could try https://softwareengineering.stackexchange.com/. This site is not meant for that kind of thing.
This is a common difficulty with new Java developers.
The point you are missing is that the last entry in an array is at position a.length-1. Similarly for Strings
Here's an improved version to demonstrate.
public static String reverse(String a) {
char[] newWord = new char[a.length()];
for (int i = 0, j = a.length() - 1; i < a.length(); i++, j--) {
newWord[j] = a.charAt(i);
}
return new String(newWord);
}
You're already on the right track with your method. The one thing I will say to you is that you don't need to use an array of characters and then use something like return new String(newWord);. That's overly complicated for beginner Java in my view.
Instead, you can create an empty String and just keep appending the characters onto it as you loop through all the characters in the String you want to reverse.
So your for loop, because you're reversing the word, should begin at the end of the word being reversed (a in this case) and work backwards to index position 0 (ie. the start of the word being reversed).
Try this and see if this makes sense to you:
public static String reverse(String a) {
String reversedWord = "";
for (int index = a.length() - 1; index >= 0; index --) {
reversedWord += a.charAt(index);
}
return reversedWord;
}
This is, then, starting at the end of a, working backwards one character at a time (hence the use of index --) until we reach a point where index has gone beyond the character at index position 0 (the middle condition of index >= 0).
At each index position, we are simply taking the character from the a String and appending it onto the reversedWord String.
Hope this helps! Feel free to ask any other questions if you are stuck on this.
In your for loop, body must be as that
newWord[--j] = a.charAt(i);. It's because if the lenght of array is 8, its indexes are 0-7. So we first decrement j and then use it as array pointer.
public class Test {
public static String reverse(String a) {
int size= a.length();//size of string
char[] newWord = new char[size];//intialize
for (int i = size-1,j=0; i >=0 ; i--,j++) {//loop start from 7 to 0
newWord[j] = a.charAt(i);// and reverse string goes from 0 to 7
}
return new String(newWord);
}
public static void main(String a[]) {
String word = "abcdefgh";
System.out.println(reverse(word));
}
}
static void reverse {
String word = "Hello World";
StringBuilder str = new StringBuilder(word);
str.reverse();
System.out.println(str);
}
or you could do
new StringBuilder(word).reverse().toString()
public static void main(String[] args) {
String input = "hello world";
String output = new String();
for (int i = input.length() - 1; i >= 0; i--) {
output = output + input.charAt(i);
}
System.out.println(output);
}
package Reverse;
import java.util.*;
public class StringReverse {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a String: ");
String original = input.nextLine();
String rev = "";// Initialize as Empty String
for(int i = original.length() - 1 ; i>=0 ; i--){
rev += original.charAt(i);
}
System.out.println("Reverse form: "+rev);
}
}
I need to get a new string based on an old one and a lag. Basically, I have a string with the alphabet (s = "abc...xyz") and based on a lag (i.e. 3), the new string should replace the characters in a string I type with the character placed some positions forward (lag). If, let's say, I type "cde" as my string, the output should be "fgh". If any other character is added in the string (apart from space - " "), it should be removed. Here is what I tried, but it doesn't work :
String code = "abcdefghijklmnopqrstuvwxyzabcd"; //my lag is 4 and I added the first 4 characters to
char old; //avoid OutOfRange issues
char nou;
for (int i = 0; i < code.length() - lag; ++i)
{
old = code.charAt(i);
//System.out.print(old + " ");
nou = code.charAt(i + lag);
//System.out.println(nou + " ");
// if (s.indexOf(old) != 0)
// {
s = s.replace(old, nou);
// }
}
I commented the outputs for old and nou (new, but is reserved word) because I have used them only to test if the code from position i to i + lag is working (and it is), but if I uncomment the if statement, it doesn't do anything and I leave it like this, it keeps executing the instructions inside the for statmement for code.length() times, but my string doesn't need to be so long. I have also tried to make the for statement like below, but I got lost.
for (int i = 0; i < s.length(); ++i)
{
....
}
Could you help me with this? Or maybe some advices about how I should think the algorithm?
Thanks!
It doesn't work because, as the javadoc of replace() says:
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
(emphasis mine)
So, the first time you meet an 'a' in the string, you replace all the 'a's by 'd'. But then you go to the next char, and if it's a 'd' that was an 'a' before, you replace it once again, etc. etc.
You shouldn't use replace() at all. Instead, you should simply build a new string, using a StringBuilder, by appending each shifted character of the original string:
String dictionary = "abcdefghijklmnopqrstuvwxyz";
StringBuilder sb = new StringBuilder(input.length());
for (int i = 0; i < input.length(); i++) {
char oldChar = input.charAt(i);
int oldCharPositionInDictionary = dictionary.indexOf(oldChar);
if (oldCharPositionInDictionary >= 0) {
int newCharPositionInDictionary =
(oldCharPositionInDictionary + lag) % dictionary.length();
sb.append(dictionary.charAt(newCharPositionInDictionary));
}
else if (oldChar == ' ') {
sb.append(' ');
}
}
String result = sb.toString();
Try this:
Convert the string to char array.
iterate over each char array and change the char by adding lag
create new String just once (instead of loop) with new String passing char array.
String code = "abcdefghijklmnopqrstuvwxyzabcd";
String s = "abcdef";
char[] ch = s.toCharArray();
char[] codes = code.toCharArray();
for (int i = 0; i < ch.length; ++i)
{
ch[i] = codes[ch[i] - 'a' + 3];
}
String str = new String(ch);
System.out.println(str);
}
My answer is something like this.
It returns one more index to every character.
It reverses every String.
Have a good day!
package org.owls.sof;
import java.util.Scanner;
public class Main {
private static final String CODE = "abcdefghijklmnopqrstuvwxyz"; //my lag is 4 and I added the first 4 characters to
#SuppressWarnings("resource")
public static void main(String[] args) {
System.out.print("insert alphabet >> ");
Scanner scanner = new Scanner(System.in);
String s = scanner.next();
char[] char_arr = s.toCharArray();
for(int i = 0; i < char_arr.length; i++){
int order = CODE.indexOf(char_arr[i]) + 1;
if(order%CODE.length() == 0){
char_arr[i] = CODE.charAt(0);
}else{
char_arr[i] = CODE.charAt(order);
}
}
System.out.println(new String(char_arr));
//reverse
System.out.println(reverse(new String(char_arr)));
}
private static String reverse (String str) {
char[] char_arr = str.toCharArray();
for(int i = 0; i < char_arr.length/2; i++){
char tmp = char_arr[i];
char_arr[i] = char_arr[char_arr.length - i - 1];
char_arr[char_arr.length - i - 1] = tmp;
}
return new String(char_arr);
}
}
String alpha = "abcdefghijklmnopqrstuvwxyzabcd"; // alphabet
int N = alpha.length();
int lag = 3; // shift value
String s = "cde"; // input
StringBuilder sb = new StringBuilder();
for (int i = 0, index; i < s.length(); i++) {
index = s.charAt(i) - 'a';
sb.append(alpha.charAt((index + lag) % N));
}
String op = sb.toString(); // output
For accessing individual characters of a String in Java, we have String.charAt(2). Is there any inbuilt function to remove an individual character of a String in java?
Something like this:
if(String.charAt(1) == String.charAt(2){
//I want to remove the individual character at index 2.
}
You can also use the StringBuilder class which is mutable.
StringBuilder sb = new StringBuilder(inputString);
It has the method deleteCharAt(), along with many other mutator methods.
Just delete the characters that you need to delete and then get the result as follows:
String resultString = sb.toString();
This avoids creation of unnecessary string objects.
You can use Java String method called replace, which will replace all characters matching the first parameter with the second parameter:
String a = "Cool";
a = a.replace("o","");
One possibility:
String result = str.substring(0, index) + str.substring(index+1);
Note that the result is a new String (as well as two intermediate String objects), because Strings in Java are immutable.
No, because Strings in Java are immutable. You'll have to create a new string removing the character you don't want.
For replacing a single char c at index position idx in string str, do something like this, and remember that a new string will be created:
String newstr = str.substring(0, idx) + str.substring(idx + 1);
String str = "M1y java8 Progr5am";
deleteCharAt()
StringBuilder build = new StringBuilder(str);
System.out.println("Pre Builder : " + build);
build.deleteCharAt(1); // Shift the positions front.
build.deleteCharAt(8-1);
build.deleteCharAt(15-2);
System.out.println("Post Builder : " + build);
replace()
StringBuffer buffer = new StringBuffer(str);
buffer.replace(1, 2, ""); // Shift the positions front.
buffer.replace(7, 8, "");
buffer.replace(13, 14, "");
System.out.println("Buffer : "+buffer);
char[]
char[] c = str.toCharArray();
String new_Str = "";
for (int i = 0; i < c.length; i++) {
if (!(i == 1 || i == 8 || i == 15))
new_Str += c[i];
}
System.out.println("Char Array : "+new_Str);
To modify Strings, read about StringBuilder because it is mutable except for immutable String. Different operations can be found here https://docs.oracle.com/javase/tutorial/java/data/buffers.html. The code snippet below creates a StringBuilder and then append the given String and then delete the first character from the String and then convert it back from StringBuilder to a String.
StringBuilder sb = new StringBuilder();
sb.append(str);
sb.deleteCharAt(0);
str = sb.toString();
Consider the following code:
public String removeChar(String str, Integer n) {
String front = str.substring(0, n);
String back = str.substring(n+1, str.length());
return front + back;
}
You may also use the (huge) regexp machine.
inputString = inputString.replaceFirst("(?s)(.{2}).(.*)", "$1$2");
"(?s)" - tells regexp to handle newlines like normal characters (just in case).
"(.{2})" - group $1 collecting exactly 2 characters
"." - any character at index 2 (to be squeezed out).
"(.*)" - group $2 which collects the rest of the inputString.
"$1$2" - putting group $1 and group $2 together.
If you want to remove a char from a String str at a specific int index:
public static String removeCharAt(String str, int index) {
// The part of the String before the index:
String str1 = str.substring(0,index);
// The part of the String after the index:
String str2 = str.substring(index+1,str.length());
// These two parts together gives the String without the specified index
return str1+str2;
}
By the using replace method we can change single character of string.
string= string.replace("*", "");
Use replaceFirst function of String class. There are so many variants of replace function that you can use.
If you need some logical control over character removal, use this
String string = "sdsdsd";
char[] arr = string.toCharArray();
// Run loop or whatever you need
String ss = new String(arr);
If you don't need any such control, you can use what Oscar orBhesh mentioned. They are spot on.
Easiest way to remove a char from string
String str="welcome";
str=str.replaceFirst(String.valueOf(str.charAt(2)),"");//'l' will replace with ""
System.out.println(str);//output: wecome
public class RemoveCharFromString {
public static void main(String[] args) {
String output = remove("Hello", 'l');
System.out.println(output);
}
private static String remove(String input, char c) {
if (input == null || input.length() <= 1)
return input;
char[] inputArray = input.toCharArray();
char[] outputArray = new char[inputArray.length];
int outputArrayIndex = 0;
for (int i = 0; i < inputArray.length; i++) {
char p = inputArray[i];
if (p != c) {
outputArray[outputArrayIndex] = p;
outputArrayIndex++;
}
}
return new String(outputArray, 0, outputArrayIndex);
}
}
In most use-cases using StringBuilder or substring is a good approach (as already answered). However, for performance critical code, this might be a good alternative.
/**
* Delete a single character from index position 'start' from the 'target' String.
*
* ````
* deleteAt("ABC", 0) -> "BC"
* deleteAt("ABC", 1) -> "B"
* deleteAt("ABC", 2) -> "C"
* ````
*/
public static String deleteAt(final String target, final int start) {
return deleteAt(target, start, start + 1);
}
/**
* Delete the characters from index position 'start' to 'end' from the 'target' String.
*
* ````
* deleteAt("ABC", 0, 1) -> "BC"
* deleteAt("ABC", 0, 2) -> "C"
* deleteAt("ABC", 1, 3) -> "A"
* ````
*/
public static String deleteAt(final String target, final int start, int end) {
final int targetLen = target.length();
if (start < 0) {
throw new IllegalArgumentException("start=" + start);
}
if (end > targetLen || end < start) {
throw new IllegalArgumentException("end=" + end);
}
if (start == 0) {
return end == targetLen ? "" : target.substring(end);
} else if (end == targetLen) {
return target.substring(0, start);
}
final char[] buffer = new char[targetLen - end + start];
target.getChars(0, start, buffer, 0);
target.getChars(end, targetLen, buffer, start);
return new String(buffer);
}
*You can delete string value use the StringBuilder and deletecharAt.
String s1 = "aabc";
StringBuilder sb = new StringBuilder(s1);
for(int i=0;i<sb.length();i++)
{
char temp = sb.charAt(0);
if(sb.indexOf(temp+"")!=1)
{
sb.deleteCharAt(sb.indexOf(temp+""));
}
}
To Remove a Single character from The Given String please find my method hope it will be usefull. i have used str.replaceAll to remove the string but their are many ways to remove a character from a given string but i prefer replaceall method.
Code For Remove Char:
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
public class Removecharacter
{
public static void main(String[] args)
{
String result = removeChar("Java", 'a');
String result1 = removeChar("Edition", 'i');
System.out.println(result + " " + result1);
}
public static String removeChar(String str, char c) {
if (str == null)
{
return null;
}
else
{
return str.replaceAll(Character.toString(c), "");
}
}
}
Console image :
please find The Attached image of console,
Thanks For Asking. :)
public static String removechar(String fromString, Character character) {
int indexOf = fromString.indexOf(character);
if(indexOf==-1)
return fromString;
String front = fromString.substring(0, indexOf);
String back = fromString.substring(indexOf+1, fromString.length());
return front+back;
}
BufferedReader input=new BufferedReader(new InputStreamReader(System.in));
String line1=input.readLine();
String line2=input.readLine();
char[] a=line2.toCharArray();
char[] b=line1.toCharArray();
loop: for(int t=0;t<a.length;t++) {
char a1=a[t];
for(int t1=0;t1<b.length;t1++) {
char b1=b[t1];
if(a1==b1) {
StringBuilder sb = new StringBuilder(line1);
sb.deleteCharAt(t1);
line1=sb.toString();
b=line1.toCharArray();
list.add(a1);
continue loop;
}
}
When I have these kinds of questions I always ask: "what would the Java Gurus do?" :)
And I'd answer that, in this case, by looking at the implementation of String.trim().
Here's an extrapolation of that implementation that allows for more trim characters to be used.
However, note that original trim actually removes all chars that are <= ' ', so you may have to combine this with the original to get the desired result.
String trim(String string, String toTrim) {
// input checks removed
if (toTrim.length() == 0)
return string;
final char[] trimChars = toTrim.toCharArray();
Arrays.sort(trimChars);
int start = 0;
int end = string.length();
while (start < end &&
Arrays.binarySearch(trimChars, string.charAt(start)) >= 0)
start++;
while (start < end &&
Arrays.binarySearch(trimChars, string.charAt(end - 1)) >= 0)
end--;
return string.substring(start, end);
}
public String missingChar(String str, int n) {
String front = str.substring(0, n);
// Start this substring at n+1 to omit the char.
// Can also be shortened to just str.substring(n+1)
// which goes through the end of the string.
String back = str.substring(n+1, str.length());
return front + back;
}
I just implemented this utility class that removes a char or a group of chars from a String. I think it's fast because doesn't use Regexp. I hope that it helps someone!
package your.package.name;
/**
* Utility class that removes chars from a String.
*
*/
public class RemoveChars {
public static String remove(String string, String remove) {
return new String(remove(string.toCharArray(), remove.toCharArray()));
}
public static char[] remove(final char[] chars, char[] remove) {
int count = 0;
char[] buffer = new char[chars.length];
for (int i = 0; i < chars.length; i++) {
boolean include = true;
for (int j = 0; j < remove.length; j++) {
if ((chars[i] == remove[j])) {
include = false;
break;
}
}
if (include) {
buffer[count++] = chars[i];
}
}
char[] output = new char[count];
System.arraycopy(buffer, 0, output, 0, count);
return output;
}
/**
* For tests!
*/
public static void main(String[] args) {
String string = "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG";
String remove = "AEIOU";
System.out.println();
System.out.println("Remove AEIOU: " + string);
System.out.println("Result: " + RemoveChars.remove(string, remove));
}
}
This is the output:
Remove AEIOU: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG
Result: TH QCK BRWN FX JMPS VR TH LZY DG
For example if you want to calculate how many a's are there in the String, you can do it like this:
if (string.contains("a"))
{
numberOf_a++;
string = string.replaceFirst("a", "");
}
Without going through the char sequence is there any way to reverse String in Java
Try this,
String s = "responses";
StringBuilder builder = new StringBuilder(s);
System.out.println(builder.reverse());
You can use the StringBuilder#reverse() method:
String reverse = new StringBuilder(originalString).reverse().toString();
Use StringBuilder's or StringBuffer's method... reverse()
public class StringReverse
{
public static void main(String[] args)
{
String string=args[0];
String reverse = new StringBuffer(string).reverse().toString();
System.out.println("\nString before reverse: "+string);
System.out.println("String after reverse: "+reverse);
}
}
StringBuffer is thread-safe, where as StringBuilder is Not thread safe..... StringBuilder was introduced from Java 1.5, as to do those operations faster which doesn't have any Concurrency to worry about....
Try reverse() method:
StringBuilder stringName = new StringBuilder();
String reverse = stringName.reverse().toString();
You may use StringBuilder..
String word = "Hello World!";
StringBuilder sb = new StringBuilder(word);
System.out.print(sb.reverse());
If we have to do it:
Without going through the char sequence
One easy way with iteration will be:
public String reverse(String post) {
String backward = "";
for(int i = post.length() - 1; i >= 0; i--) {
backward += post.substring(i, i + 1);
}
return backward;
}
You can use String buffer to reverse a string.
public String reverse(String s) {
return new StringBuffer(s).reverse().toString();
}
one more interesting way to do this is recursion.
public String reverse(String s) {
if (s.length() <= 1) {
return s;
}
return reverse(s.substring(1, s.length())) + s.charAt(0);
}
This is a way to do so using recursion -
public static String reverse(String s1){
int l = s1.length();
if (l>1)
return(s1.substring(l-1) + reverse(s1.substring(0,l-1)));
else
return(s1.substring(0));
}
Using minimal API support. A simple algorithm.
static String reverse(String str) {
char[] buffer = str.toCharArray();
for (int i = 0; i < buffer.length/2; ++i){
char c = buffer[i];
buffer[i] = buffer[buffer.length-1-i];
buffer[buffer.length-1-i] = c;
}
return new String(buffer);
}
Here I have a sample of the same using substring method and o(n) without using any nethods from string . I am aware that using substring will hold complete string memory.
for(int i = 0; i < s.length(); i++) {
s = s.substring(1, s.length() - i) + s.charAt(0) + s.substring(s.length() - i);
System.out.println(s);
}
This might help you!!
public class RevString {
public static void main(String[] args) {
String s="jagan";
String rev="";
for (int i=s.length()-1;i>=0;i--) {
rev=rev+s.charAt(i);
}
System.out.println("Reverse String is: "+rev);
}
}
I have not seen any easy way.
Here is the suitable way to do:
Using the loop:
String d = "abcdefghij";
char b[] = new char[d.length()];// new array;
int j=0; // for the array indexing
for(int i=d.length()-1;i>=0;i--){
b[j] = d.charAt(i); // input the last value of d in first of b i.e. b[0] = d[n-1]
j++;
}
System.out.println("The reverse string is: "+String.valueOf(b));
Output is
The reverse string is: jihgfedcba
The simple logic is:
array[i] = array[n-i];
where i is the Iteration and n is the total length of array
Is it possible to reverse String in Java without using any of the temporary variables like String, Char[] or StringBuilder?
Only can use int, or int[].
String reverseMe = "reverse me!";
for (int i = 0; i < reverseMe.length(); i++) {
reverseMe = reverseMe.substring(1, reverseMe.length() - i)
+ reverseMe.substring(0, 1)
+ reverseMe.substring(reverseMe.length() - i, reverseMe.length());
}
System.out.println(reverseMe);
Output:
!em esrever
Just for the fun of it, of course using StringBuffer would be better, here I'm creating new Strings for each Iteration, the only difference is that I'm not introducing a new reference, and I've only an int counter.
The objects of the Java String class are immutable - their contents cannot be altered after being created.
You will need at least two temporary objects - one for the final result and one for the intermediate values - even if you do find a way to avoid using a local variable.
EDIT:
That said, since you can use int[] you may be able to cheat.
Since char can be assigned to int, you can use String.charAt() to create an int array with the character values in reverse order. Or you may be allowed to use String.toCharArray() to get a char array that will be copied over to your int[] temporary.
Then you use the variable that holds the reference to your original string (or the result variable, if you are allowed one) to start from an empty string (easily obtainable with a direct assignment or String.substring()) and use String.concat() to create the final result.
In no case, however, will you be able to swap the characters in-place as you would do in C/C++.
EDIT 2:
Here's my version which does not use StringBuffer/Builders internally:
int r[] = new int[s.length()];
int idx = r.length - 1;
for (int i : s.toCharArray()) {
r[idx--] = i;
}
s = s.substring(0, 0);
for (int i : r) {
s = s.concat(String.valueOf((char)i));
}
String s = "Hello World!";
for(int i = 0; i < s.length(); i++)
{
s = s.substring(1, s.length() - i) + s.charAt(0) + s.substring(s.length() - i);
}
System.out.println(s); // !dlroW olleH
No temporary variables! :)
One of many ways:
String str = "The quick brown fox jumps over the lazy dog";
int len = str.length();
for (int i = (len-1); i >= 0; --i)
str += str.charAt(i);
str = str.substring(len);
System.out.println(str);
public String reverseStr(String str) {
if (str.length() <= 1) {
return str;
}
return reverseStr(str.substring(1)) + str.charAt(0);
}
Because you can use an int, you can assign an int a char value:
String aString = "abc";
int intChar = aString.charAt(0);
You will have to convert from the int back to the char to assign it to aString.charAt(2).
I'm sure you can figure it out from there.
First append the string to itself in reverse manner. Then take the second half out of it.
public class RevString {
public static void main(String[] args) {
String s="string";
for(int i=s.length()-1;i>=0;i--){
s+=s.charAt(i);
}
s=s.substring(s.length()/2, s.length());
System.out.println(s);
}
}
Without using any collection,StringBulider, StringBuffer or temp array reverse the string. Simple and crisp:
public static void main(String[] args) {
String test = "Hello World";
String rev = "";
Pattern p = Pattern.compile("[\\w|\\W]");
Matcher m = p.matcher(test);
while (m.find()) {
rev = m.group()+rev;
}
System.out.println("Reverse==" + rev);
}
Output
Reverse==dlroW olleH
Hope it helps :)
public class Test {
static St`enter code here`ring reverseString(String str) {
for (int i = 0; i < str.length() / 2; i++) {
if (i == 0) {
str = str.charAt(str.length() - 1 - i) + str.substring(i + 1, str.length() - 1 - i) + str.charAt(i);
} else {
str = str.substring(0, i) + str.charAt(str.length() - 1 - i)
+ str.substring(i + 1, str.length() - 1 - i) + str.charAt(i)
+ str.substring(str.length() - i, str.length());
}
}
return str;
}
public static void main(String args[]) {
String s = "ABCDE";
System.out.println(Test.reverseString(s));
}
}
String str = "Welcome";
for(int i=0;i<str.length();){
System.out.print(str.charAt(str.length()-1));
str = str.substring(0,str.length()-1);
}
Except for loop variables.
You can use class java.lang.StringBuilder:
String reservedString = new StringBuilder(str).reserve().toString();