how to inverse a string - java

I have this homework from the school, however Im not sure Im doing wrong the second array does not takes the values of the first one, can you help me please?
public static void main(String[] rpp) {
String[] word = new String[7];
word[0] = "D";
word[1] = "E";
word[2] = "N";
word[3] = "T";
word[4] = "I";
word[5] = "S";
word[6] = "T";
String[] inverseWord = new String[7];
inverseWord[0] = "";
inverseWord[1] = "";
inverseWord[2] = "";
inverseWord[3] = "";
inverseWord[4] = "";
inverseWord[5] = "";
for(int x = word.length;x <= 0;x--){
for(int y = 0;y <= word.length;y++){
inverseWord[y] = word[x];
}
}
System.out.print(Arrays.toString(inverseWord) + "\n");
}

Array-indexes start at 0. Which means that if the length is L, the last index in the array will be (L-1).
This means that instead of int x = word.length you need to write int x = word.length - 1 and instead of y <= word.length you need to write y < word.length or y <= word.length - 1.
Also, the condition in your outer loop should be x >= 0, not x <= 0.

You don't need two for loops
x should be greater than equal to 0 not less than
public static void main(String[] rpp) {
String[] word = new String[7];
word[0] = "D";
word[1] = "E";
word[2] = "N";
word[3] = "T";
word[4] = "I";
word[5] = "S";
word[6] = "T";
String[] inverseWord = new String[7];
inverseWord[0] = "";
inverseWord[1] = "";
inverseWord[2] = "";
inverseWord[3] = "";
inverseWord[4] = "";
inverseWord[5] = "";
for (int x = word.length - 1; x >= 0; x--) {
inverseWord[(word.length-1) - x] = word[x];
}
System.out.print(Arrays.toString(inverseWord) + "\n");
}

The condition on your outer for loop should be
x >= 0

Rewrite the for loop used for reversing using 2 variables.This is the simplest and most basic method.
for(int i=word.length-1,int j=0;i>=0,j>=0;i--,j++) //loop for reversing
{
inverseWord[j] = word[i];
}
for(int i=0;i>=0;i++) // for displaying the inverseword array
{
System.out.print(inverseWord[j];
}

You can use StringBuilder to append individual characters into a String. The String "DENTIST" can be broken up into characters of reverse order with the use of the charAt method in the String class and a for loop.
public class MainClass {
public static void main(String[] args) {
String word = "DENTIST";
StringBuilder inverseWord = new StringBuilder();
for (int i = word.length()-1; i >= 0; i--) {
inverseWord.append(word.charAt(i));
}
System.out.println(inverseWord);
}
}

Related

Java remove parts from a words

Hello I can't make this work, I am given a main word followed by another sub words if the word is contained in the main word the part should be deleted.
//Example
//fmrog (in.nextLine)(main word)
//4 (in.nextInt)(the amount of sub words)
//roc(in.nextLine)(not contained)
//gor(in.nextLine)(not contained)
//rog(in.nextLine)(contained)
//ogr(in.nextLine)(not contained)
//result:fm
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
StringBuilder mainWord = new StringBuilder(in.nextLine);
int n = in.nextInt();
StringBuilder MainWord2 = new StringBuilder(mainWord);
in.nextLine();
for (int i = 0; i < n; i++) {
String subWord = in.nextLine();
int chars = subWord.length();
if (chars> mainWord.length()){
continue;
}
for (int j = 0; j < subWord.length(); j++) {
int r = 0;
for (int k = 0; k < mainWord.length(); k++) {
r++;
if (k > MainWord2.length() - 1) {
break;
}
if (MainWord2.charAt(k) == subWord.charAt(j)) {
break;
}
}
if (r <= MainWord2.length() && MainWord2.charAt(r-1) == subWord.charAt(j)) {
MainWord2.deleteCharAt(r - 1);
if (j >= subWord.length() -1 ) {
mainWord = MainWord2;
break;
}
}
if (r > MainWord2.length()) {
MainWord2 = mainWord;
break;
}
}
}
System.out.println(mainWord);
}
}
Honestly I am stucked maybe there is an easier way to solve this. The main thing is that when I write a case like : "super 2 pe surr" At the end at "surr" the two StringBuilders start to act as one when I delete chatAt at one of them the other one changes also
No need to make it so complex.
String input = // complete user input
String[] words = String.split(input);
String mainWord = words[0];
int numWords = Integer.parseInt(words[1]); // this variable isn't needed
for(int i = 2; i < words.length; i++) {
if (mainWord contains words[i]) {
mainWord = mainWord.replace(words[i], ""); // remove subword from mainword
}
}
At the end, mainWord will be the original mainWord without any subwords that were entered later.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
in.nextLine();
String[] words = new String[n];
for (int i = 0; i <n ; i++) {
words[i] = in.nextLine();
}
String mainWord = words[0];
for (int i = 1; i <words.length ; i++) {
if (mainWord.contains(words[i])){
mainWord = mainWord.replace(words[i], "");
}
}
System.out.println(mainWord);
}
}
Here but the thing is if the letters are not one next to another it doesnt remove the subword.

How do i Reverse Capitalize And Separate Words By Line Using String In Java?

The input is: i love cake
The output needs to be: Cake Love I
But the actual result is: I Love Cake
What I've got:
import java.util.regex.Pattern;
public class yellow {
static String reverseWords(String str){
Pattern pattern = Pattern.compile("\\s");
String[] temp = pattern.split(str);
String result = "";
for (int i = 0; i < temp.length; i++) {
if (i == temp.length - 1)
result = temp[i] + result;
else
result = " " + temp[i] + result;
}
return result;
}
public static void main(String[] args){
String source = "i love cake";
StringBuffer res = new StringBuffer();
String[] strArr = source.split(" ");
for (String str : strArr) {
char[] stringArray = str.trim().toCharArray();
stringArray[0] = Character.toUpperCase(stringArray[0]);
str = new String(stringArray);
res.append(str).append(" ");
}
System.out.print(res.toString());
}
}
What am I doing wrong?
for (String str : strArr) {
}
This loops forward. What you want is to loop backwards, or to place elements into the string backwards. I recommend you loop backwards and print as you go:
for (int i = strArr.length - 1; i >= 0; i--) {
char[] stringArray = strArr[i].trim().toCharArray();
stringArray[0] = Character.toUpperCase(stringArray[0]);
System.out.println(new String(stringArray));
}
Or, you could use that convenient reverseWords method that you never use anywhere... though looping backwards is faster. Probably.
[EDITED]
Call this for each line with string s, then print a line break (If you have multiple sentences & expect them in their own lines).
void reverseCamel(String s){
String[] ar = s.split("\\s+");
for(int i = ar.length - 1;i>=0;i--){
ar[i][0] = Character.toUpperCase(ar[i][0]);
System.out.print(ar[i] + " ");
}
}
Here is what i did.
public class Main {
public static void main(String[] args) {
reverse("I Love Cake");
}
public static void reverse( String string){
String[] word =string.split(" "); // split by spaces
int i = word.length-1;
while (i>=0){
// System.out.print(word[i].toUpperCase()+" ");//if you want in upper case
System.out.print(word[i]+" ");
i--;
}
}
}
First of all you have to reverse the String.
String[] words = source.split("\\s");
String reversedString = "";
for(int i = words.length -1; i>=0; i--){
reversedString += words[i] + " ";
}
Then, you know that the ASCII code of 'a' character is 97, 'A' is 65. To convert from lower case to capital you substract 32. All capitals are between 65 and 92. All small letters are between 97 and 124.
You want to capitalize only letters at the beginning of a word (preceded by a space or first letter).
String capitalCase = "";
for (int i = 0; i < reversedString.length(); i++) {
char c = reversedString.charAt(i);
if (c >= 97 && c <= 124) {
if (i == 0) c -= 32;
else if ((reversedString.charAt(i - 1) + "").equals(" ")) c -= 32;
}
capitalCase += c;
}
And here you go now System.out.println(capitalCase);
Overall, you will have the following code:
import java.util.Scanner;
public class yellow {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter a string:");
String source = s.nextLine();
String[] words = source.split("\\s");
String reversedString = "";
for (int i = words.length - 1; i >= 0; i--) {
reversedString += words[i] + " ";
}
String capitalCase = "";
for (int i = 0; i < reversedString.length(); i++) {
char c = reversedString.charAt(i);
if (c >= 97 && c <= 124) {
if (i == 0) c -= 32;
else if ((reversedString.charAt(i - 1) + "").equals(" ")) c -= 32;
}
capitalCase += c;
}
System.out.println(capitalCase);
}
}
Output:
Enter a string:
i love cake
Cake Love I
Java 8 * Apache Commons Lang
public static String reverseWordsInString(String str) {
List<String> words = Pattern.compile("\\s+").splitAsStream(str)
.map(StringUtils::capitalize)
.collect(LinkedList::new, LinkedList::addFirst, (a, b) -> a.addAll(0, b));
return words.stream().collect(Collectors.joining(StringUtils.SPACE));
}
Java 8
public static String reverseWordsInString(String str) {
List<String> words = Pattern.compile("\\s+").splitAsStream(str)
.map(word -> Character.toUpperCase(word.charAt(0)) + word.substring(1).toLowerCase())
.collect(LinkedList::new, LinkedList::addFirst, (a, b) -> a.addAll(0, b));
return words.stream().collect(Collectors.joining(" "));
}

Java words reverse

I am new to Java and I found a interesting problem which I wanted to solve. I am trying to code a program that reverses the position of each word of a string. For example, the input string = "HERE AM I", the output string will be "I AM HERE". I have got into it, but it's not working out for me. Could anyone kindly point out the error, and how to fix it, because I am really curious to know what's going wrong. Thanks!
import java.util.Scanner;
public class Count{
static Scanner sc = new Scanner(System.in);
static String in = ""; static String ar[];
void accept(){
System.out.println("Enter the string: ");
in = sc.nextLine();
}
void intArray(int words){
ar = new String[words];
}
static int Words(String in){
in = in.trim(); //Rm space
int wc = 1;
char c;
for (int i = 0; i<in.length()-1;i++){
if (in.charAt(i)==' '&&in.charAt(i+1)!=' ') wc++;
}
return wc;
}
void generate(){
char c; String w = ""; int n = 0;
for (int i = 0; i<in.length(); i++){
c = in.charAt(i);
if (c!=' '){
w += c;
}
else {
ar[n] = w; n++;
}
}
}
void printOut(){
String finale = "";
for (int i = ar.length-1; i>=0;i--){
finale = finale + (ar[i]);
}
System.out.println("Reversed words: " + finale);
}
public static void main(String[] args){
Count a = new Count();
a.accept();
int words = Words(in);
a.intArray(words);
a.generate();
a.printOut();
}
}
Got it. Here is my code that implements split and reverse from scratch.
The split function is implemented through iterating through the string, and keeping track of start and end indexes. Once one of the indexes in the string is equivalent to a " ", the program sets the end index to the element behind the space, and adds the previous substring to an ArrayList, then creating a new start index to begin with.
Reverse is very straightforward - you simply iterate from the end of the string to the first element of the string.
Example:
Input: df gf sd
Output: sd gf df
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
public class Count{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter string to reverse: ");
String unreversed = scan.nextLine();
System.out.println("Reversed String: " + reverse(unreversed));
}
public static String reverse(String unreversed)
{
ArrayList<String> parts = new ArrayList<String>();
String reversed = "";
int start = 0;
int end = 0;
for (int i = 0; i < unreversed.length(); i++)
{
if (unreversed.charAt(i) == ' ')
{
end = i;
parts.add(unreversed.substring(start, end));
start = i + 1;
}
}
parts.add(unreversed.substring(start, unreversed.length()));
for (int i = parts.size()-1; i >= 0; i--)
{
reversed += parts.get(i);
reversed += " ";
}
return reversed;
}
}
There is my suggestion :
String s = " HERE AM I ";
s = s.trim();
int j = s.length() - 1;
int index = 0;
StringBuilder builder = new StringBuilder();
for (int i = j; i >= 0; i--) {
Character c = s.charAt(i);
if (c.isWhitespace(c)) {
index = i;
String r = s.substring(index+1, j+1);
j = index - 1;
builder.append(r);
builder.append(" ");
}
}
String r=s.substring(0, index);
builder.append(r);
System.out.println(builder.toString());
From adding debug output between each method call it's easy to determine that you're successfully reading the input, counting the words, and initializing the array. That means that the problem is in generate().
Problem 1 in generate() (why "HERE" is duplicated in the output): after you add w to your array (when the word is complete) you don't reset w to "", meaning every word has the previous word(s) prepended to it. This is easily seen by adding debug output (or using a debugger) to print the state of ar and w each iteration of the loop.
Problem 2 in generate() (why "I" isn't in the output): there isn't a trailing space in the string, so the condition that adds a word to the array is never met for the last word before the loop terminates at the end of the string. The easy fix is to just add ar[n] = w; after the end of the loop to cover the last word.
I would use the split function and then print from the end of the list to the front.
String[] splitString = str.split(" ");
for(int i = splitString.length() - 1; i >= 0; i--){
System.out.print(splitString[i]);
if(i != 0) System.out.print(' ');
}
Oops read your comment. Disregard this if it is not what you want.
This has a function that does the same as split, but not the predefined split function
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the string : ");
String input = sc.nextLine();
// This splits the string into array of words separated with " "
String arr[] = myOwnSplit(input.trim(), ' '); // ["I", "AM", "HERE"]
// This ll contain the reverse string
String rev = "";
// Reading the array from the back
for(int i = (arr.length - 1) ; i >= 0 ; i --) {
// putting the words into the reverse string with a space to it's end
rev += (arr[i] + " ");
}
// Getting rid of the last extra space
rev.trim();
System.out.println("The reverse of the given string is : " + rev);
}
// The is my own version of the split function
public static String[] myOwnSplit(String str, char regex) {
char[] arr = str.toCharArray();
ArrayList<String> spltedArrayList = new ArrayList<String>();
String word = "";
// splitting the string based on the regex and bulding an arraylist
for(int i = 0 ; i < arr.length ; i ++) {
char c = arr[i];
if(c == regex) {
spltedArrayList.add(word);
word = "";
} else {
word += c;
}
if(i == (arr.length - 1)) {
spltedArrayList.add(word);
}
}
String[] splitedArray = new String[spltedArrayList.size()];
// Converting the arraylist to string array
for(int i = 0 ; i < spltedArrayList.size() ; i++) {
splitedArray[i] = spltedArrayList.get(i);
}
return splitedArray;
}

find the value of variable given in a string

Given a equation :
433+4H8= 871
H can be anyside of equation. Find the value of H and replace it in given equation.
The output should be :
433+438=871
I have tried the following code but conversion of string to int does not work...
import java.util.Scanner;
import java.io.*;
class hole
{
public static void main(String[] args)
{
Scanner reader= new Scanner(System.in);
int[] nums= new int[3];
String str= reader.nextLine();
String str_1= str.replaceAll("=","+");
String[] split= str_1.split("[+]");
for (int k=0; k<split.length; k++)
{
String ex= split[k];
nums[k]= Integer.parseInt(ex);
}
}
}
4H8 isn't an integer, so parseInt won't work on it.
It seems like you still have a bit of a way to go on this, so I won't spoil your fun by giving you the code, just some ideas.
Assuming the equation is always X + Y = Z, which X, Y and Z being some integers, one of which can contain an H...
You need to have a couple of cases:
If the H is in X, you can get X by subtracting Y from Z.
If the H is in Y, you can get Y by subtracting X from Z.
If the H is in Z, you can get Z by adding X and Y.
But this still doesn't give you H. For this, you can simply find the position of the H in the string we have and extract the digit at that position in the number calculated above.
So before calling parseInt, you should look for the H and simply store the string instead if you find it.
parseInt also doesn't like spaces, so you should remove those in some way or another.
If equations aren't always in the form X + Y = Z (i.e. you can also have subtraction, multiplication, division and/or multiple terms), it gets a bit more complicated.
Why would you not just subtract the final answer minus the first number and build the third number. Splitting the string is redundant as you can just use simple math to solve for x.
871-433 = 438
h=3
public static void main(String[] args)
{
int a = 433;
int b = 871;
int c = b - a;
String s = "4H8";
char x;
int location = 0;
for(int i = 0; i < s.length(); i++)
{
char d = s.charAt(i);
if(d.isDigit()){
}
else{
location = i;
x = d;
}
}
String solve = c.toString();
System.out.println(x + "=" + solve.charAt(location) );
}
Try this (comments are self explanatory):
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int[] nums = new int[3];
int varIndex = 0;
int result = 0;
String str = reader.nextLine();
//remove spaces and split into 3 parts based on symbols
String[] components = str.replaceAll(" ", "").split("\\+|=");
for (int i = 0; i < components.length; i++) {
try {
nums[i] = Integer.parseInt(components[i]);
} catch (Exception e) {
varIndex = i; //this component contains "H"
}
}
//Calculate the value of the number which has "H"
switch (varIndex) {
case 0:
result = nums[2] - nums[1]; break;
case 1:
result = nums[2] - nums[0]; break;
case 2:
result = nums[0] + nums[1]; break;
}
nums[varIndex] = result;
//Print the output
System.out.println(nums[0] + " + " + nums[1] + " = " + nums[2]);
System.out.println("H = " + (String.valueOf(result)).charAt(components[varIndex].indexOf('H')));
}
Try below program , This works only for input a+b=c format
Below program is giving correct output
import java.util.Scanner;
public class Hole {
public static void main(String args[])
{
int hLocation = 0;
int result;
char hValue;
Scanner in=new Scanner(System.in);
String str=in.nextLine().replaceAll(" ", "");
String[] split= str.split("[+=]");
for(int i=0;i<split.length;i++){
if(split[i].contains("H")){
hLocation=i;
}
}
if(hLocation==0){
result=Integer.parseInt(split[2])-Integer.parseInt(split[1]);
}else if(hLocation==1){
result=Integer.parseInt(split[2])-Integer.parseInt(split[0]);
}
else{
result=Integer.parseInt(split[0])+Integer.parseInt(split[1]);
}
hValue= String.valueOf(result).charAt(1);
str=str.replace('H', hValue);
System.out.println(str);
}
}
Try this:
public static void main(String[] args)
{
Scanner reader = new Scanner(System.in);
int[] nums = new int[3];
boolean[] isNum = new boolean[3];
String str = reader.nextLine();
// String str_1= str.replaceAll("=","+");
String[] split = str.split("[+=]");
int i = 0;
for (int k = 0; k < split.length; k++) {
try {
String s = split[k];
isNum[k] = true;
nums[i] = Integer.parseInt(s);i++;
} catch (NumberFormatException e) {
// TODO: handle exception
isNum[k] = false;
}
}
int tot ;
if(str.indexOf("H")>str.indexOf("=")){
tot = nums[1] + nums[0];
}else{
tot = nums[1] - nums[0];
}
for (int k = 0; k < split.length; k++) {
if(!isNum[k]){
int indx = split[k].indexOf("H");
String h = Integer.toString(tot).charAt(indx)+"";
h = str.replace("H",h);
System.out.println("New expression :"+h);
}
}
}

How to get string if length is more than 50?

In java how to split a string value, if >50 then the string after the last succeeding comma should be assigned to another String.
Eg:
String test = "ASDFGHJKLPOIUYTRE YUIOOPPKMABJFD AJDJDJDJD, DJDJDJD DJDJDJ, JDJDJD UYUYUAU JKBFDKJBDKJJK";
the above string's length is 88.
after 50th character #59th "," is presented so string should be split with the last succeeding "comma" and the output should be as follows:
ASDFGHJKLPOIUYTRE YUIOOPPKMABJFD AJDJDJDJD, DJDJDJD DJDJDJ,
JDJDJD UYUYUAU JKBFDKJBDKJJK
thanks in advance!!!
I have tried as follows:
if(add1.length() > 50){
for(int i=50;i<add1.length();i++){
if(add1.charAt(i)== ','){
add2 = add1.substring((i+1),add1.length());
add1 = add1.substring(0,i);
}
}
}
You can do this using the indexOf method of strings to find the next comma, then manually splitting:
if(test.length() > 50){
int comma = test.indexOf(',', 50);
if(comma >= 0){
//Bit before comma
String partOne = test.substring(0, comma);
//Bit after comma
String partTwo = test.substring(comma);
//Do Something
}
}
String someString = "";
int lastCommaPosition = someString.lastIndexOf(",");
if(lastCommaPosition > 50){
String firstPart = someString.substring(0,lastCommaPosition +1);
String secondPart = someString.substring(lastCommaPosition);
}
Try subString(), indexOf(), replace()
if(test.length() > 50)
{
System.out.println(test.substring(test.lastIndexOf(",") + 1, test.length()).replace(",", ""));
}
String test = "ASDFGHJKLPOIUYTRE YUIOOPPKMABJFD AJDJDJDJD, DJDJDJD DJDJDJ, JDJDJD UYUYUAU JKBFDKJBDKJJK";
int index = 0;
if (test.length() > 50) {
index = test.indexOf(",", 50);
}
String firstString = test.substring(0, index + 1);
String secondString = test.substring(index + 1);
System.out.println(firstString);
System.out.println(secondString);
// Java version
public class StrSub {
private String s = "ASDFGHJKLPOIUYTRE YUIOOPPKMABJFD AJDJDJDJD, DJDJDJD DJDJDJ, JDJDJD UYUYUAU JKBFDKJBDKJJK";
private void compute() {
int i = 50, p = 0, len = s.length();
String s1, s2;
for (i = 50; i < len; i++) {
if (s.charAt(i) == ',') {
p = i;
break;
}
}
System.out.println(p);
s1 = s.substring(0, p+1);
s2 = s.substring(p+1);
System.out.println(s1);
System.out.println(s2);
}
public static void main(String[] args) {
StrSub s = new StrSub();
s.compute();
}
}
Try this...
int index = 0;
String[] out= new String[test.length()/50]();
for(int i=50, j=0; test.length() > 50 ; j++){
if(test.length>i){
index = test.indexOf(",",i);
}
out[j] = test.subString(0,index);
test = test.subString(index+1, test.length());
}
// Cover the boundary condition
if(test.length() > 0){
out[j] = test;

Categories