Simple Java String Reversal - java

I'm having trouble with this problem.
Here is the code I wrote out:
package com.jdewey.rvrs;
import java.util.Scanner;
public class Reverse {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Enter your string: ");
String userIn = console.nextLine();
int inLength = userIn.length();
stringRvrs(userIn, inLength);
}
public static void stringRvrs(String x, int length){
for(int i = 1; i <= length; i++){
int y = -1 * i + length;
System.out.print(x.substring(y));;
}
}
}
It's supposed to output "tset" if you were to input "test"
Please help!

It makes more sense to just write your loop to start at the end of the string, and also to print each character using charAt instead of substring. See below:
public static void stringRvrs(String x, int length){
String result = "";
for(int i = length - 1; i >= 0; i--){
result = result + x.charAt(i);
}
System.out.println(result);
}
Of course, there is an easier way using library functions to reverse a string (see here: Reverse a string in Java), but I assume this is a learning exercise for you so I corrected the code instead of just linking to an easy way to do it.

Try StringBuilder as in:
public static void stringRvrs(String x){
char [] all = x.toCharArray();
StringBuilder concate = new StringBuilder();
for(int i = all.length-1;i >= 0;i--){
concate = concate.append(String.valueOf(all[i]));
}
System.out.println(x+" reversed to "+concate);
}
No need to pass int length as an parameter to the method.

you can simply use stringBuilder.reverse();
your method should look like this after the changes,
public static void stringRvrs(String x, int length){
StringBuilder sb = new StringBuilder(x);
System.out.println(sb.reverse());
}
There is no need to pass the length of the String as an argument since it can be found using string.length(); at any point of time.

Related

Repeating a string using a for loop

I'm fairly new to programming. I'm trying to repeat the word in a given string the amount of times by a given number in the same string. I have decided to loop through the string and add each char to a new string to print out but I'm getting an out of index error.
final String string = "Hello";
final int num = 3;
int number = string.length() * num;
String str = "";
for (int i = 0; i < number; i++) {
str += string.charAt(i);
}
System.out.println(str);
Zero-based index
You are getting the error because the value of i is going beyond the last index available in Hello. The last index in Hello is "Hello".length() - 1 whereas the value of i is going beyond this value because of your loop terminating condition:
i < string.length() * num;
By the way, if you want to repeat Hello 3 times, you should do it as
for(int i = 0; i < num; i ++){
System.out.print(string);
}
Demo:
public class Main {
public static void main(String[] args) {
final String string = "Hello";
final int num = 3;
for (int i = 0; i < num; i++) {
System.out.print(string);
}
}
}
String#repeat
With Java 11+, you can do it without using a loop by using String#repeat:
System.out.println(string.repeat(num));
Demo:
public class Main {
public static void main(String[] args) {
final String string = "Hello";
final int num = 3;
System.out.println(string.repeat(num));
}
}
Just keep it simple
String string = "Hello";
int num = 3;
for (int i = 0; i < num; i++) {
System.out.println(string);
}
If you want to have your result in a new String you can just do this :
String string = "Hello";
int num = 3;
String res = "";
for (int i = 0; i < num; i++) {
res += string;
}
System.out.println(res);
Just adding this in here since you stated you're learning.
Java has a StringBuilder class, super easy to use
And according this this induvial class using StringBuilder is incredibly more efficient than concatenate.
StringBuilder vs String concatenation in toString() in Java

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();

Java program to reverse a string not working?

I have written a piece of code to reverse a string in Java. However, its showing multiple errors and I wish to understand where it is that I am going wrong. I know that there are alternative methods of reversing a string. However, I want to know where I am going wrong with my code.
public class RevString {
public static void main(String[] args)
{
public Reverse (String str)
{
int len = str.length();
String rev;
for (int i = 0; i <= len; i++)
{
rev = str[i] + rev;
}
System.out.println(rev);
}
Reverse("Canyon");
}
}
Errors:
Multiple markers at this line
- Syntax error on token ")", ; expected
- Syntax error on token "(", . expected
- Reverse cannot be resolved to a type
- Illegal modifier for parameter str; only final is
The method Reverse(String) is undefined for the type
RevString
Could someone provide me with a resolution?
There are many errors in your code :
For loop condition should be i < len
String rev should be initialized to "" (empty string), else it will throw error when you try to append another string to it.
You can't access characters in a string using str[i], use str.charAt(i) instead.
You are trying to initialize a function (Reverse) inside another function (main), you must initialize it outside the main function.
Also, here is a simple one liner for string reversal:
new StringBuilder(str).reverse().toString()
A good tip might be to use the StringBuilder class whenever you want to do any kind of string manipulation in Java.
Your code has many issues:
You are declaring the method Reverse() inside the main method.
You also need to initialize rev to an empty string.
You can use str.charAt(i) to access each character of the string.
Your for loop goes beyond the string if you use i <= len; so it
should be i < len;.
Your Reverse() method should be static since you are calling it in main
method (which is static)
Here is working code.
public class RevString {
public static void main(String[] args) {
Reverse("Canyon");
}
public static void Reverse (String str) {
int len = str.length();
String rev="";
for (int i = 0; i < len; i++) {
rev = str.charAt(i) + rev;
}
System.out.println(rev);
}
}
Please see the below code:
public class Hello {
public static String reverse (String str){
int len = str.length();
String rev="";
char[] strArray = str.toCharArray();
for (int i = 0; i < len; i++)
{
rev = strArray[i] + rev;
}
return rev;
}
public static void main(String[] args) {
String result = reverse("Canyon");
System.out.println("Reversed String: " + result);
}
}
public class reverseString
{
public static void main(String[] args)
{
System.out.println("Welcome to the the string reverser.");
System.out.println("Here is where a person may put is a sentence and the orintation" +
" of the words is reversed.");
Scanner keyboard = new Scanner(System.in);
String word = keyboard.nextLine();
int lengthOf = word.length();
int j = 0;
char loopStr;
String LoopStr;
String Nstr = "";
for(int n = lengthOf; n >0 ;n--)
{
j = n;
LoopStr = word.substring(j-1,j);
Nstr = Nstr + LoopStr;
}
System.out.println(Nstr);
}
}

Array opposite string. Must use arrays [duplicate]

This question already has answers here:
Reverse a string in Java
(36 answers)
Closed 4 years ago.
How do i make an array with the opposite letters of the first array im making? For example if the string is "Hello", i want to use arrays to print out "olleH". When i try to return the variables it tells me "String index out of range: -1". Can anyone please tell me why? This is my code so far:
public class april{
public static void main(String [] args){
System.out.println("What do you want backwards?");
System.out.println("Your new word is " + reverse(IO.readString()));
}
public static String reverse(String original){
char [] letters = new char [original.length()];
char [] opp = new char [original.length()];
char c= 'a';
char d= 'a';
String word= " ";
String opposite= " ";
for (int x=0;x<original.length();x++){
c = original.charAt(x);
letters[x]= c;
if (x!=0){
d = original.charAt(-x-1);
opp[-x]=d;
}
else if (x==0){
d = original.charAt(-1);
opp[x]= d;
}
word += letters[x];
opposite += opp[x];
}
return word;
return opposite;
You're close! You just need to start at the other end of the String for the second array (with proper syntax):
for (int x = 0; x < original.length(); x++) {
char c = original.charAt(x);
char d = original.charAt(original.length() - x - 1);
letters[x] = c;
opp[original.length() - x - 1] = d;
}
Note: You also have to subtract 1 because both arrays and string indices are 0-indexed.
I think this is a great way to do it.
public class Main {
public static void main(String[] args) {
String reversed = reverse("Hello");
System.out.println(reversed);
}
private static String reverse(String word) {
byte[] array = word.getBytes();
int i = 0;
int j = array.length - 1;
byte tmp;
while (j > i) {
tmp = array[j];
array[j] = array[i];
array[i] = tmp;
j--;
i++;
}
return new String(array);
}
}
Your method receives a String and returns another String, so you don't need to work with arrays at all, just use the reverse method of the StringBuilder class.
public static String reverse(String original) {
return new StringBuilder(original).reverse().toString();
}

Cannot find symbol error Java

So I was creating this random string generator:
public class Test {
public static void main(String[] args) {
String strings = "abcdefghijklmnopqrstuvwxyz1234567890!##$%&()ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Random generator = new Random(System.currentTimeMillis());
int stringLength = strings.length()-1;
Character character;
for (int i = 0; i < stringLength; i++) {
Double test = new Double(Math.random());
character = strings.charAt(test.intValue());
String outputString = outputString.concat(character.toString());
}
System.out.println(outputString);
}
}
I went an compiled it using javac Test.java, and it gave me the error outputString might not have been initialised for lines 14 and 16. So I added the String keyword to line 14, and now it's telling me
cannot find symbol: variable outputString
Why is this so?
EDIT:
Okay so I took up the suggestions, and this is the code currently:
public class Test {
public static int randomInt(int min, int max, long seed) {
Random rand = new Random(seed);
int randomNum = rand.nextInt((max-min)+1) - min;
return randomNum;
}
public static void main(String[] args) {
String strings = "abcdefghijklmnopqrstuvwxyz1234567890!##$%&()ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int stringLength = strings.length()-1;
Character character;
for (int i = 0; i < stringLength; i++) {
Double test = new Double(randomInt(0, stringLength, System.currentTimeMillis()));
character = strings.charAt(test.intValue());
System.out.print(character);
}
}
}
The code runs without errors, but it doesn't print anything.
I'm currently using Command Prompt to compile it.
You are defining the outputString only inside of the for loop. It will not be available outside.
You could output the characters directly:
for (int i = 0; i < stringLength; i++) {
Double test = new Double(Math.random());
character = strings.charAt(test.intValue());
System.out.print(character);
}
System.out.println();
If you insist on concatenating a String in a loop, please use StringBuilder instead.
The next problem you will run into:
Double test = new Double(Math.random());
strings.charAt(test.intValue());
That will always get the the first character. The double will be between 0 (inclusive) and 1 (exclusive).
You need to create a random integer between 0 and the length of your alphabet.
The compiler is correctly telling that outputString is not declared correctly. The outputString is declared within the for loop, but you are trying to print the value outside.
A quick way to fix this would be to declare outputString outside the for loop by having outputString = "";
outputString is only defined within the block of the for loop, so once you exit it, it no longer exists. To make sure that your code works, define it outside the loop:
String outputString = "";
for (int i = 0; i < stringLength; i++) {
Double test = new Double(Math.random());
character = strings.charAt(test.intValue());
outputString += character.toString();
}
System.out.println(outputString);
It is because you are calling outputString.concat before you have intialized it
try
String outputString = "";
outputString = outputString.concat(character.toString());`
I managed to get it to work using the following code:
import java.util.Random;
public class Test{
public static void print(String str) {
System.out.print(str);
}
public static int randomInt(int min, int max) {
Random rand = new Random(System.currentTimeMillis());
int randomNum = rand.nextInt((max-min)+1) - min;
return randomNum;
}
public static void main(String[] args) throws InterruptedException {
String strings = "abcdefghijklmnopqrstuvwxyz1234567890!##$%&()ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int len = strings.length() - 1;
StringBuilder outputString = new StringBuilder(len);
for (int i = 0; i < len; i++) {
Double test = new Double(randomInt(0, len));
Integer value = test.intValue();
if (value <= len) {
//print(value.toString()); For testing purposes
outputString.append(strings.charAt(value));
Thread.sleep(1);
}
else {i--;}
}
print(outputString + "\n");
}
}

Categories