Reversing A String. Every other word reversing - java

So i've got a for loop that's reversing every other word in a string. I can't determine which condition is causing this.
for (int i = 0; i < words.length; i++)
{
stringBuilder.append(words[(words.length-1)-i]);
stringBuilder.reverse()
}
newMessage = stringBuilder.toString();
return Message

stringBuilder.reverse() reverse the whole string that you are currently building at each iteration.
Try:
for (int i = 0 ; i < words.length ; i++) {
String word = words[(words.length-1)-i];
String reverse = new StringBuilder(word).reverse().toString();
stringBuilder.append(reverse).append(" ");
}
Or even simpler, reversing at the end:
for (int i = 0 ; i < words.length ; i++) {
stringBuilder.append(words[(words.length-1)-i]).append(" ");
}
newMessage = stringBuilder.reverse().toString();
Edit based on comments:
for (String w : words) {
String reverse = new StringBuilder(w).reverse().toString();
stringBuilder.append(reverse).append(" ");
}
newMessage = stringBuilder.toString();

stringBuilder.reverse(); is reversing the whole word comment that line and your code wont reverse your new message

var string = "hello world";
function reverseWords(string) {
var words = string.split(' '),
finals = [];
words.forEach(function(word) {
finals.push(word.split('').reverse().join(''););
});
return finals.join(' ');
}
reverseWords(string); // "olleh dlrow"

First of all, your loop is more complex then it needs to be. If you want to reverse words starting from the end, you should just use the loop index to do that, you don't need the (words.length-1)-i calculation.
Another thing, when you call reverse() on a StringBuilder you are reversing the whole string not just the appended portion. What you can do is use a temp StringBuilder to perform the reversal and a temp String variable to separate reversal from appending.
Something like this:
StringBuilder reversedBuilder = new StringBuilder();
for (int i = words.length - 1; i >= 0; i --)
{
String reversed = reversedBuilder.append(words[i]).reverse().toString(); // reverse the word
stringBuilder.append(reversed).append(" ");
reversedBuilder.setLength(0); // clear the reversed
}
If you want, you can do this in a single line of code (added with comments for clarification):
for (int i = words.length - 1; i >= 0; i --)
{
stringBuilder.append(new StringBuilder() // create a temp string builder
.append(words[i]) // add the current word to temp string builder
.reverse() // reverse the current word in the temp string builder
.toString()) // add the reversed word to stringBuilder
.append(" "); // add the space to stringBuilder
}

Related

manipulating the strings to make new strings with the respective indexes

input :have anic eday
String[] words = sb.toString().split("//s");
StringBuilder sbFinal = new StringBuilder();
for(int i=0;i<words[0].length() ;i++){
for(int j=0;j<words.length;j++){
sbFinal.append(words[j].charAt(i));
}
}
return sbFinal.toString() ;
output : have anic eday
I have a number of strings which I need to convert in the form where a new set of strings are printed ( space seperated ) which are formed by the respective chars of each strings given .
desired output : hae and via ecy
for example we have 3 words of 4 chars each , we want 4 words of 3 chars each .
have anic eday =>hae and via ecy
we pick 1st char from all 3 words to make the new first word .
I used the code shown above but it prints the input as output itself .
Use simple for loops and an array:
public class SO {
public static void main(String args[]) {
String input = "have anic eday ";
// Split the input.
String[] words = input.split("\\s");
int numberOfWords = words.length;
int wordLength = words[0].length();
// Prepare the result;
String[] result = new String[wordLength];
// Loop over the new words.
for (int i = 0; i < wordLength; i++) {
// Loop over the characters in each new word.
for (int j = 0; j < numberOfWords; j++) {
// Initialize the new word, if necessary.
String word = result[i] != null ? result[i] : "";
// Append the next character to the new word.
String newChar = Character.toString(words[j].charAt(i));
result[i] = word + newChar;
}
}
for (String newWord : result) {
System.out.println(newWord);
}
}
}
Output:
hae
and
via
ecy
Although answered, I made up a more similar version to what you have originally designed, just with sysout instead of return, but change to your needs, or just adjust the .split() line:
String sb = "have anic eday";
String[] words = sb.split("\\s"); //you need to use BACKWARDSLASH "\\s" to get it to work.
StringBuilder sbFinal = new StringBuilder();
for (int i = 0; i < words[0].length(); i++) {
for (int j = 0; j < words.length; j++) {
sbFinal.append(words[j].charAt(i));
}
sbFinal.append(" ");
}
System.out.println(sbFinal.toString());
You split with "//s", however " " or "\\s" seems to work perfectly fine.

How to get the common first substrings In two Strings

I need some help, I have two Strings and I want to get the first occurrence of common substrings.
1st String : abacdefghi
2nd String : abaciopiss
I want to get the substring
substring : abac
Thank you everyone.
It maybe isn't the best solution but my attempt would be to find the first matching characters in each string and then continue to check the following characters if they are still the same:
private static String extractFirstEqual(String a, String b) {
//Split your string into an array of characters
String[] arr = a.split("");
String[] brr = b.split("");
StringBuilder result = new StringBuilder();
//Iterate over both arrays
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < brr.length; j++) {
//Find first matching character
if (arr[i].equals( brr[j])) {
//While there are more characters in both arrays and the characters keep matching, append them
// to the result
while (arr[i].equals(brr[j]) && i < arr.length && j < brr.length) {
result.append(arr[i]);
i++;
j++;
}
return result.toString();
}
}
}
return result.toString();
}

Java find difference between characters in StringBuffer

I'm working on an Anagram program and I'm currently working on a method called diff which should return a StringBuffer containing the chars that are in the first StringBuffer but not in the second one. So for example if the StringBuffers are abba and acca, then my diff method should return bb. So far I currently have loop with an if statement but it's not working. Any help would be appreciated. Thanks
public StringBuffer diff(){
StringBuffer diffVal = null;
for (int i =0; i < sBuffer1.length(); i++){
String let1 = String.valueOf(sBuffer1);
if (sBuffer2.indexOf(let1) == -1 ){
}
}
return diffVal;
I think you are trying to use a loop to examine one character by one character in sBuffer1. But String let1 = String.valueOf(sBuffer1); gives you the entire string of sBuffer1.
What you need is String let1 = sBuffer1.substring(i, i + 1) to take a single character from sBuffer1 to check if it exists in sBuffer2.
For example:
public static StringBuffer diff(StringBuffer sBuffer1, StringBuffer sBuffer2) {
StringBuffer diffVal = new StringBuffer();
for (int i = 0; i < sBuffer1.length(); i++) {
String let1 = sBuffer1.substring(i, i + 1); // get the character from sBuffer1
if (sBuffer2.indexOf(let1) == -1) {
diffVal.append(let1); // append the character to the diff
}
}
return diffVal;
}
ok this might work, your logic was a little bit wrong, this code is straight forward. search for the character if it doesn't exist in the second string buffer add it to the result SF.
public StringBuffer diff(){
StringBuffer diffVal = new StringBuffer();//initialize before you use it.
for (int i =0; i < sBuffer1.length(); i++){
String let1 = String.valueOf(sBuffer1.charAt(i))//get the character at the ith position.
if (sBuffer2.indexOf(let1) == -1 ){
diffVal.append(let1);
}
}
return diffVal;
}
Try this.
StringBuilder diffVal= new StringBuilder();
StringBuffer sBuffer1 = new StringBuffer("abbad");//input 1
StringBuffer sBuffer2 = new StringBuffer("acca");//input 2, you can ignore if you have already passed/defined these
for (int i =0; i < sBuffer1.length(); i++){
if(i >= sBuffer2.length()){//handles difference in input string length
diffVal.append(sBuffer1.substring(i, sBuffer1.length()));
break;
}
if (sBuffer1.charAt(i) != sBuffer2.charAt(i)) {
diffVal.append(sBuffer1.charAt(i));
}
}
System.out.println(diffVal);// I am printing it here
the out put is : bbd
One recommendation here is use StringBuilder if you the strings you are using here are not required to be synchronized

How to print String buffer lines from last to first order

I have requirement to print String buffer lines as last to first order.
Example :toString of Stringbuffer method is printing below output:
this
is
some
text
Desired output:
text
some
is
this
What you could do is to create an array, iterate over it.
String s = new String("this\nis\nsome\ntext");
String []tokens = s.split("\n");
for(int i = tokens.length - 1; i >= 0; --i)
System.out.println(tokens[i]);
StringBuffer s = new StringBuffer("this\nis\nsome\ntext");
String []tokens = s.toString().split("\n");
for(int i = tokens.length - 1; i >= 0; --i)
System.out.println(tokens[i]);
A better memory less approach would be.
StringBuffer s = new StringBuffer("this\nis\nsome\ntext");
String word = "";
for(int i = s.length() - 1; i >= 0; --i)
{
if(s.charAt(i) != '\n')
{
word = s.charAt(i) + word;
}
else{
System.out.println(word);
word = "";
}
}
if(!word.equals(""))
System.out.println(word);
StringBuffer is a final class so you cannot extend it and override its toString() method to achieve what you want to do. You will have to handle it in your code.
you will have to do something like this :
public class Reverse {
public static void main(String[] args) {
// TODO Auto-generated method stub
StringBuffer s =new StringBuffer();
s.append("this\nis\nsome\ntext");
String[] rev = s.toString().split("\n");
for(int i=rev.length-1;i>=0;i--) {
System.out.println(rev[i]);
}
}
}
o/p :
text
some
is
this
Hope that helps
StringBuffer does not, by itself, have the capacity to return the lines the way you want them. You can either get the whole string from the buffer and use string.split("\n") to split it into an array, which you can then iterate over back to front, or create a class of your own that provides a function that handles such an operation
This should probably do it:
String[] lines = myStringBuffer.toString().split(System.lineSeparator()); //or use any other character for splitting
for(int i=lines.length; i>0; i--) {
System.out.println(lines[i-1]);
}
StringBuffer or String also has a lastIndexOf.
StringBuffer buf = new StringBuffer("this\nis\nsome\ntext");
final String EOL = "\n"; // Or "\r\n" or even "\u0085".
for (int pos = buf.length(); pos > 0; ) {
int before = buf.lastIndexOf(EOL, pos);
before = before == -1 ? 0 : before + EOL.length();
String line = buf.substring(before, pos);
System.out.println(buf);
pos = before - EOL.length();
}
Note: StringBuilder is better.

Java: Accumulate output pattern in string variable?

There is probably a question that covers this, but I haven't found it in searching. The idea is to display a pattern given user input for the character and number of lines like this:
x
xx
xxx
xxxx
xxxx
xxx
xx
x
But I need to use JOptionPane to do this. Here is what I have:
import javax.swing.JOptionPane;
public class loopPattern {
public static void main(String[] args) {
String in, num, output1 = null, output2 = "";
int lines = 0;
int i, n = 1;
in = JOptionPane.showInputDialog("Please enter the character for the pattern:");
num = JOptionPane.showInputDialog("Please enter the number of lines in the pattern:");
lines = Integer.parseInt(num);
for (i=1; i<=lines; i++) {
for (n=1; n<=lines; n++) {
output1 = (n +"\n");
}
}
for (i=lines; i>=1; i--){
for (n=lines; n>=1; n--){
output2 = (n +"\n");
}
}
JOptionPane.showMessageDialog(null, output1 +output2);
}
}
I have to then make it repeat this pattern each time the user hits "Ok" and quit when they hit "Cancel". I think I can do that if I could just figure out the accumulating in a string variable thing. Thanks so much for the help.
Accumulating in a string variable is called a StringBuilder. It allows you to quickly append things into the StringBuilder from which you can call toString() to transform it back to a String.
StringBuilder sb = new StringBuilder();
for (i=1; i<=lines; i++) {
for (n=1; n<=lines; n++) {
sb.append(n +"\n");
}
}
if you can not use a StringBuilder, then use a String variable and assign it the value of itself with another string using the "+" operator. This can be shorthanded with "+="
String string = new String();
string = string + "stuff to go on the string";
// or as a shorthand equivalent
string += "stuff to go on the string";
/// loop example
String myoutput = new String();
for (i=1; i<=lines; i++) {
for (n=1; n<=lines; n++) {
myoutput += n +"\n";
}
}
As a high level approach, you could try this. Create two StringBuilder instances. Loop up until the desired lines is hit. For each iteration, append an X into the first StringBuilder and then append to entire contents of that StringBuilder into the other one (via toString) with a \n for the newline. After that loop finishes, append in 2 empty lines for the separators. Then, loop until the first StringBuilder is empty, removing the last char for each iteration (via deleteCharAt(sb.length()-1)) and appending the entire content into the other StringBuilder again via toString plus \n. When done, the second StringBuilder should have the patten you desire.
int lines = 4;
StringBuilder sb = new StringBuilder();
StringBuilder pattern = new StringBuilder();
for(int i = 0; i < lines; i++){
sb.append("X");
pattern.append(sb.toString() + "\n");
}
pattern.append("\n\n");
pattern.append(sb.toString() + "\n");
while(sb.length() > 0){
sb.deleteCharAt(sb.length() - 1);
pattern.append(sb.toString() + "\n");
}
System.out.println(pattern.toString());
If using a StringBuilder is too advanced you can get the same effect simply using a string:
String output1 = "";
for (i=1; i<=lines; i++) {
for (n=1; n<=lines; n++) {
output1 = output1.concat(n +"\n");
// note the below commented out code should also work:
//output1 = output1 + n + "\n";
}
}
This is much less efficient then using a StringBuilder though since a new string will be created and assigned to output1 for each iteration of the inner loop.
Your loop shuold look more like:
for (i=1; i<=lines; i++) {
for (n=0; n<i; n++) {
output1 += in;
}
output += "\n";
}
assuming you can't use StringBuilder (which, per other posts, is a better option).

Categories