how to revearse a string? - java

Cant seem to get this to work. trying to get it to read backwards like a mirror without using the buffer class.
public static void main(String[] args) {
Scanner keyboard = new Scanner(System. in);
System.out.println("Enter a phrase:");
String phrase = keyboard.nextLine();
String Rphrase;
int n = phrase.length();
int r = 0;
do{
n--; r++;
Rphrase[r] = phrase[n];
}while(n >= 0);
System.out.println(Rphrase);

I have provided 4 ways of getting the output of the String reversed.
Option 1:
Just iterate the String backwards.
for (int i=phrase.length()-1; i>-1; i--) {
System.out.print(foo.charAt(i));
}
Option 2:
If you would like to put it in the other buffer you can do:
char[] buffer = new char[phrase.length()];
index = 0;
for (int i=phrase.length()-1; i>-1; i--) {
buffer[index++] = foo.charAt(i);
}
Option 3:
You said you didnt want to use the buffer class (which I think you're referring to StringBuffer so I'm assuming you dont want to use StringBuilder either) so here is how you can do it strictly with Strings (which is rather inefficient, because a new String is constructed each iteration):
String foo = "";
for (int i=phrase.length()-1; i>-1; i--) {
foo += foo.charAt(i);
}
Option 4:
A most likely more efficient way of doing this though, is by using StringBuilder:
StringBuilder sb = new StringBuilder(foo.length());
for (int i=foo.length()-1; i>-1; i--) {
sb.append(foo.charAt(i));
}
String reverse = sb.toString();
OR
Refer to this for very simple String reversal with a StringBuilder:
Reverse a string in Java

Try:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System. in);
System.out.println("Enter a phrase:");
String phrase = keyboard.nextLine();
String rPhrase = "";
for (int i = phrase.length() - 1; i >= 0; i--)
rPhrase += phrase.charAt(i);
System.out.println(rPhrase);
}

This is what you need.
String reverse = "";
String toReverse = "hello";
for(int i = 0; i<toReverse.length();i++){
reverse += toReverse.substring(i,i+1);
}
System.out.println(reverse);

Some hints, rather than a complete solution...
Your loop will run for one more iteration when n = 0, which will lead to trying to access index -1. So perhaps try n > 0 as your condition.
And what would happen if the string is empty? It would also try to access index -1, before ever getting to the loop. Perhaps you should put the condition at the beginning.
String doesn't support the [] operator - try:
Rphrase += phrase.charAt(n);
In which case you may as well get rid of r.

you have to make a decrement so it can read its value back to front
for (int i = name.length() - 1, j = 0; i >= 0; i--, j++) {
newName[j] = name.charAt(i); enter code here
}
System.out.println(newName);
}

Simply use StringBuilder.reverse
str = new StringBuilder(str).reverse().toString();

Related

Reversing strings in Java (loops) until "done"

this is a lab for class I'm trying to do. Here's the instructions:
Write a program that takes in a line of text as input, and outputs that line of text in reverse. The program repeats, ending when the user enters "Done", "done", or "d" for the line of text.
Ex: If the input is:
"Hello there
Hey
done"
the output is:
"ereht olleH
yeH"
And here's what I have right now:
public class LabProgram {
public static void main(String[] args) {
/* Type your code here. */
Scanner scnr = new Scanner(System.in);
String[] inputs = new String[100];
String input;
int i = 0;
while (true) {
input = scnr.nextLine();
if(input.equals("Done") || input.equals("done") || input.equals("d"))
break;
inputs[i] = input;
i++;
}
for (int j = 0; j < i; j++) {
int length = inputs[j].length();
String reverse = "";
for (int k = length - i; k >= 0; k--) {
reverse = reverse + inputs[j].charAt(k);
}
System.out.print("\n" + reverse);
}
}
}
Current output
What am I doing wrong??
Iterate through the array, and reverse elements at every index.
This solution is time consuming but does your job
for (int j = 0; j < inputs.lenght; j++) {
int length = inputs[j].length();
char a;
String rev = "";
for(int i =0; i< length; i++){
a = inputs[j].charAt(i);
rev = a + rev;
}
System.out.println(rev);
}
*Try to use StringBuilder And use method reverse -- #Artur Todeschini
To add to what Artur said, an ArrayList of StringBuilders could do the trick quite well:
for(StringBuilder nextEntry : stringBuilderList)
{
nextEntry.reverse();
}
The enhanced for-loop will go through each entry in the ArrayList, and the StringBuilder's reverse will change the order of the letters.
EDIT TO SHOW FORMATTING
ArrayList<StringBuilder> stringBuilderList= new ArrayList<>();
*note. given that this is for a lab, its probably for learning purposes and using built-in classes that does all the work for you are usually not the intended solution. -- #experiment unit 1998X
Try to use StringBuilder
And use method reverse
This is another "ArrayList and StringBuilder-less" version.
Create two Strings, one filled and one empty:
String nextString = stringArray[i],
template = new String();
Loop through the length of the String, adding the next character in from the end each time through.
int length = nextString.length() - 1;
for(int j = 0; j < length; j++)
{
template += nextString.charAt(length - j);
}
Add the whole String to the String array's index
stringArray[i] = template;
NOTE
This is an inner loop for a String array and is NOT complete code

Create array with reversed words from user string

I am creating a program in which a user enters a string of words (Ex: I love you), and the program returns an array of the words in the string spelled backwards (Ex: I evol ouy). However, I cannot get my code to properly compile, and tried debugging, but cannot see where the problem is.
I tried to look for similar problems here on Slack, but the problems are found were concerned with rearranging words from a string, (ex: you I love), and I cannot find a problem similar to mine, involving turning string into an Array and then manipulating the array.
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string to see it in reverse: ");
String userEntry = sc.nextLine();
char[] entryToChar = userEntry.toCharArray();
System.out.println(Arrays.toString(entryToChar));
String[] splitInput = userEntry.split(" ");
String reverseWord = "";
int temp;
String[] reverseString = new String[splitInput.length];
for (int i = 0; i < splitInput.length; i++)
{
String word = splitInput[i];
for (int j = word.length()-1; j >= 0; j--)
{
reverseWord = reverseWord + word.charAt(j);
}
for (int k = 0; k < splitInput.length; k++) {
temp = splitInput[i];
splitInput[i] = reverseWord[j];
reverseWord[j] = temp;
}
} System.out.println("Your sttring with words spelled backwards is " + reverseWord[j]);
I am avoiding using the 'StringBuilder' method as I have not yet studied it, and trying to see if I can get the new string using swapping, as in the code below:
temp = splitInput[i];
splitInput[i] = reverseWord[j];
reverseWord[j] = temp;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String word, reverseWord;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string to see it in reverse: ");
String userEntry = sc.nextLine();
userEntry: I love you
String[] splitInput = userEntry.split(" ");
splitInput: [I, love, you]
for (int i = 0; i < splitInput.length; i++)
{
word = splitInput[i];
reverseWord = "";
for (int j = word.length()-1; j >= 0; j--)
{
reverseWord = reverseWord + word.charAt(j);
}
splitInput[i] = reverseWord;
}
splitInput: [I, evol, uoy]
System.out.println("Your string with words spelled backwards is: " + String.join(" ", splitInput));
}
}
Your string with words spelled backwards is: I evol uoy
Your code is not getting compiled because tmp variable is declared as int while splitInput[i] is String.
The other problem is variable j is outside its block scope from where you are trying to access.
Make your logic clear before writing code to achieve correct result.
A good Java programmer should know which tools exist in the language and make use of them in her/his design appropriately. I would suggest to use the class StringBuilder, which has a method for reversing the string. Your program could look like this:
while in.hasNext() {
StringBuilder sb = in.next();
sb.reverse();
System.out.println(sb.toString());
}
If you want to write the reverse function yourself for practice then you can simply define a method that takes a string and returns a reversed string and call that method in place of sb.reverse().
Please know that String in Java is an immutable object. You cannot modify it directly. You can have modified copies returned.
StringBuilder on the other hand allows the programmer to modify the object directly as you can see in the code above.
You need to split original string into an array and then reverse each one and insert into the new array, here you can use StringBuilder as good practice.
class Testarray{
public static void main(String args[]){
String str = "I am Engineer";
String[] spArray = str.split(" ");
String farr[] = new String[spArray.length];
for(int i=0;i<spArray.length;i++){
String split = spArray[i];
farr[i]=reverseString(split);
}
for(int i=0;i<farr.length;i++){
System.out.println(farr[i]);
}
}
public static String reverseString(String str){
char ch[]=str.toCharArray();
String rev="";
for(int i=ch.length-1;i>=0;i--){
rev+=ch[i];
}
return rev;
}
}
There are a few things going on here, and I think in some places you're mixing up between strings and arrays.
Let's try to break this problem down into smaller problems.
First, we need to reverse a single word. Your first inner loop (the one that uses j) does that, so let's extract it into its own method:
public static String reverseWord(String word) {
String reverseWord = "";
for (int j = word.length()-1; j >= 0; j--) {
reverseWord = reverseWord + word.charAt(j);
}
return reverseWord;
}
Although, you should note that concatenating strings like that in a loop isn't great for performance, and using a StringBuilder would probably be faster (although with such a small application, it probably won't be noticeable):
public static String reverseWord(String word) {
StringBuilder reverseWord = new StringBuilder(word.length());
for (int j = word.length()-1; j >= 0; j--) {
reverseWord = reverseWord.append(word.charAt(j));
}
return reverseWord.toString();
}
Once you have that, you can split the input string (like you did), revere each word, and join them back together:
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string to see it in reverse: ");
String userEntry = sc.nextLine();
String[] splitInput = userEntry.split(" ");
for (int i = 0; i < splitInput.length; i++) {
splitInput[i] = reverseWord(splitInput[i]);
}
System.out.println("Your sttring with words spelled backwards is " +
String.join(" ", splitInput));
All you need is to split your original sentence into separate words and use StringBuilder.reverse() to get words in reverse:
public static void main(String... args) {
String str = getSentenceFromConsole();
System.out.println("Your string with words spelled backwards is '" + reversLettersInWords(str) + '\'');
}
private static String getSentenceFromConsole() {
try (Scanner scan = new Scanner(System.in)) {
System.out.print("Enter a string to see it in reverse: ");
return scan.nextLine();
}
}
private static String reversLettersInWords(String str) {
return Arrays.stream(str.split("\\s+"))
.map(word -> new StringBuilder(word).reverse().toString())
.collect(Collectors.joining(" "));
}
i try with your code
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string to see it in reverse: ");
String userEntry = sc.nextLine();
String[] splitInput = userEntry.split(" ");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < splitInput.length; i++) {
String word = splitInput[i];
for (int j = word.length() - 1; j >= 0; j--) {
sb.append(word.charAt(j));
}
sb.append(" ");
}
System.out.println("Your sttring with words spelled backwards is " + sb.toString());
here i remove all access line of code....
String input = "i love you";
StringBuilder input1 = new StringBuilder();
input1.append(input);
input1 = input1.reverse();
System.out.println(input1);
You can use this implementation to try to reverse the string elements in the array.

Problems with stringBuilder.append().charAt in Java

I know that it exists, but my teacher wants me to do it manuallyI am trying to reverse my a stringBuilder so that the characters I have inside go in reverse order, sometimes the stringBuilder is of a single character, that is why as you can see there is an if that indicates when the characters of the stringBuilder should be turned over. This is what I have at the moment.
if ( sB.length ()> 1) {
for (int i = sB.length () - 1; i> = 0; i--) {
sB.append().charAt(i);
sB.deleteCharAt (i);
}
}
I know sB.reverse() exists, but my teacher wants me to do it manually and how you can see i don't know how to implement this two method's at once. If anyone can help me please. Thanks!
then in that case use this
StringBuilder str = new StringBuilder();
str.append("yourstring");
for(int i = str.length()-1 ; i>=0; i--)
{
str.append(str.charAt(i)).deleteCharAt(i);
}
if you want to reverse your string why dont you use
StringBuilder str = new StringBuilder();
str.append("yourstring");
str.reverse();
swap it two by two if you arent allowed to use reverse() method
StringBuilder sb = new StringBuilder("abcde");
for (int i = 0; i < sb.length()/2; i++) {
char tmp = sb.charAt(i);
sb.setCharAt(i, sb.charAt(sb.length() - 1 - i));
sb.setCharAt(sb.length() - 1 - i, tmp);
}
System.out.println(sb.toString());
Use this code to do it manually.
public class Reverse {
public static void main(String args []) {
String rev = "This should be reversed";
StringBuilder stb = new StringBuilder();
int i = rev.length()-1;
while (i != -1) {
char re = rev.charAt(i);
stb.append(re);
i--;
}
System.out.println(stb);
}
}

Find common alphabets in two strings using for loop

I am trying to find the common characters in two strings just by using the for loop. The below code is working fine, if I provide two completely different strings ex.one and two but if I provide two strings with same input ex.teen and teen it doesn't work as expected.
import java.util.Scanner;
public class CommonAlphabets {
public static void main(String[] args) {
try(Scanner input = new Scanner(System.in)){
System.out.println("Enter String one ");
String stringOne = input.nextLine();
System.out.println("Enter String two ");
String StringTwo = input.nextLine();
StringBuffer sb = new StringBuffer();
for(int i=0;i<stringOne.length();i++){
for(int j=0;j<StringTwo.length();j++){
if(stringOne.charAt(i)== StringTwo.charAt(j)){
sb.append(stringOne.charAt(i));
}
}
}
System.out.println("Common characters are " +sb.toString());
}
}
}
Should I create another nested for loop to find duplicates in the StringBuffer or is there a better way to handle this scenario.
You do not need an inner for loop but use contains instead
String stringOne = "one";
String stringTwo = "one";
StringBuilder sb = new StringBuilder();
for(int i=0;i<stringOne.length() && i < stringTwo.length ();i++){
if(stringOne.contains(String.valueOf(stringTwo.charAt(i))) &&
!sb.toString().contains(String.valueOf(stringTwo.charAt(i)))){
// check already added
sb.append(stringTwo.charAt(i));
}
}
System.out.println (sb.toString());
edit
check to make sure char to be added does not already exist in StringBuilder -
Could use a Set instead
If using a Set
Set<Character> set = new HashSet<> ();
your logic could be simplified to
if(stringOne.contains(String.valueOf(stringTwo.charAt(i)))){
set.add(stringTwo.charAt(i));
}
You can use Set for it.
Set<Character> set = new HashSet<>();
for(int i = 0; i<stringOne.length(); i++) {
for(int j = 0; j < StringTwo.length(); j++) {
if(stringOne.charAt(i) == StringTwo.charAt(j)){
set.add(stringOne.charAt(i));
}
}
}
StringBuilder sb = new StringBuilder();
for (Character c : set) {
sb.append(c);
}
System.out.println("Common characters are " + sb);
well your approach is fine as the result is showing what you are expecting there fore that code is fine, but you need to stop the duplication , therefore you have to write the code for 'sb' variable so that it will remove duplicates or write code in loop so that it wont provide duplicate.
as your code is becoming complicated to read so i would prefer that you make a method to write code to remove duplicate it will go like
static void removeDuplicate(StringBuilder s){
for(int i=0,i<s.length-1,i++){
for(int j=i+1,j<s.length,j++){
if(s.charAt(i)==s.charAt(j)){
s.deleteCharAt(j);
}
}
}
call this method before printing
Another approach you could try is - combine the two input strings, iterate over the concatenated string and return the characters which exist in both the strings.
Using a Set will ensure you do not add characters which get repeated due to the concatenation of the strings.
Here's what I wrote -
import java.util.HashSet;
public class HelloWorld {
private static Character[] findCommonLetters(String combined, String w1, String w2) {
HashSet<Character> hash = new HashSet<>();
for(char c: combined.toCharArray()) {
if(w1.indexOf(c) != -1 && w2.indexOf(c) != -1) {
hash.add(c);
}
}
return hash.toArray(new Character[hash.size()]);
}
public static void main(String []args){
// System.out.println("Hello World");
String first = "flour";
String second = "four";
String combined = first.concat(second);
Character[] result = findCommonLetters(combined, first, second);
for(char c: result) {
System.out.print(c);
}
System.out.println();
}
}
Demo here.
This is the best way to do this because it's time complexity is n so that why this is the best you could do.
import java.util.Scanner;
public class CommonAlphabets
{
public static void main(String[] args)
{
try (Scanner input = new Scanner(System.in))
{
System.out.println("Enter String one ");
String stringOne = input.nextLine();
System.out.println("Enter String two ");
String StringTwo = input.nextLine();
StringBuffer sb = new StringBuffer();
/**
* Assuming char as index of array where A-Z is from index 0 to 25 and a-z is index 26-51
*/
int[] alphabetArray1 = new int[52];
for(int i = 0, len = stringOne.length(); i < len; i++)
alphabetArray1[stringOne.charAt(i) > 94 ? stringOne.charAt(i) - 71 : stringOne.charAt(i) - 65] = 1;
int[] alphabetArray2 = new int[52];
for(int i = 0, len = StringTwo.length(); i < len; i++)
alphabetArray2[StringTwo.charAt(i) > 94 ? StringTwo.charAt(i) - 71 : StringTwo.charAt(i) - 65] = 1;
// System.out.println(Arrays.toString(alphabetArray1));
// System.out.println(Arrays.toString(alphabetArray2));
for (int i = 0; i < 52; i++)
if (alphabetArray1[i] == 1 && alphabetArray2[i] == 1)
sb.append((char) (i < 26 ? i + 65 : i + 71));
System.out.println("Common characters are " + sb.toString());
}
}
}

Java - make new string based on old one and lag

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

Categories

Resources