Multiplication formula string - java - java

I'm trying to write a code that take a string : (7+5)*(6+9)
and return the string : 7*6 + 7*9 + 5*6 + 5*9
my algorithm is to create 2 char arrays (for this example : 75,69)
and run in O^2 loop in this 2 arrays and copy value from first array , * value from second array, +. i get index of bounds exception and don't understand why.
this is my code :
String s = "((7+5)*(6+9))";
char[] ch = s.toCharArray();
char[] newCh = new char[30];
int j=0;
int blocks = 2;
int newi = 0;
for (int i=0 ; i<ch.length ; i++) {
if (ch[i]=='(' && ch[i+1]!='(') {
j=i+1;
while (blocks>0) {
if (ch[j]==')') {
blocks--;
newCh[newi]='-';
newi++;
}
if (ch[j]!='+' && ch[j]!='*' && ch[j]!=')' && ch[j]!='(') {
if (blocks==0) {
break;
}
else {
newCh[newi]=ch[j];
newi++;
}
}
j++;
}
}
continue;
}
System.out.println("new Char array : ");
for (int i=0 ; i<newCh.length ; i++) {
System.out.print(newCh[i]);
}
System.out.println();
Multy(newCh);
and my multy method :
public static char[] Multy(char[] ch) {
char[] newc = new char[50];
char[] c1 = new char[30];
char[] c2 = new char[30];
int newi = 0;
int i1 = 0;
int i2 = 0;
int flag = 0;
for (int i=0 ; i<ch.length ; i++) {
if (ch[i]!='-') {
if (flag ==0) {
c1[i1] = ch[i];
i1++;
}
else {
if (ch[i]!='-')
c2[i2]= ch[i];
i2++;
}
}
if (ch[i]=='-')
flag = 1;
}
System.out.println("In func");
System.out.print("c1 : ");
for (int i=0 ; i<c1.length ; i++) {
System.out.print(c1[i]);
}
System.out.println();
System.out.print("c2 : ");
for (int i=0 ; i<c1.length ; i++) {
System.out.print(c2[i]);
}
///////////
for (int i=0 ; i<c1.length ; i++) {
for (int j=0 ; j<c2.length ; j++) {
newc[newi]=c1[i];
newc[newi+1] = '*';
newc[newi+2] = c2[j];
newc[newi+3] = '+';
newi+=4;
}
}
System.out.print("NEWc2 : ");
for (int i=0 ; i<newc.length ; i++) {
System.out.print(newc[i]);
}
return newc;
}

in te double for loop you iterate to the end of the array (c1.length and c2.length) while you add to a number in the loop newc[newi+X] but because you loop to the end you will run out of places and you will get the IndexOutOfBoundsException...
for (int i=0 ; i<c1.length ; i++) {
for (int j=0 ; j<c2.length ; j++) {
newc[newi]=c1[i];
newc[newi+1] = '*';
newc[newi+2] = c2[j];
newc[newi+3] = '+';
newi+=4;
}
}
UPDATE:
Extra explanation :-)
If you do something like this:
public class ArrayExample {
public static void main(String[] args) {
String[] strings = new String[3];
System.out.println("strings.length = " + strings.length);
strings[4] = "foo";
}
}
The output will be:
strings.length = 3
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at nl.ivonet.ArrayExample.main(ArrayExample.java:26)
This is because I tried to assign a value at index 4 of the strings array, but the strings array was initialized with new String[3] giving it a fixed size of 3. That's what goes wrong and why your code failed.
An Array is not the same as a List. And Array is fixed size and a list not.

Related

Creating a toString method that returns an array in java

I have been recently asked to write a toString method that returns a number in an array as follows:
after every 3 digits from the right-hand side of the number it should
add a comma , but if the digits of the number were 3 or less it
doesn't add a comma.
But I've encountered a problem: The method always returns the value 0,. How can I adjust the code to return the correct format?
public class BigNum {
int[] num;
final int MAX_DIGITS = 50;
public BigNum() {
this.num = new int[MAX_DIGITS];
this.num[0] = 0;
for(int i=1 ; i<this.num.length ; i++)
this.num[i] = -1;
}
public BigNum(long n) {
int number = (int)n;
this.num = new int[MAX_DIGITS];
for (int i = 0; i < this.num.length; i++) {
num[i] = number % 10;
number /= 10;
}
}
public String toString(){
String toReturn = "";
this.num = new int[MAX_DIGITS];
for(int i=0 ; i<this.num.length ; i++)
if(this.num.length>=1 && this.num.length<=3)
toReturn = num[i] + "";
for(int j=0 ; j<this.num.length ; j+=3)
toReturn = num[j] + "," ;
return toReturn;
}
You could try the below piece of code. Remember to copy the BigNum constructor. There are a following changes made to following code:
Creating the instance array length equal to number of digits in the input and not equal to MAX_DIGITS.
Changed the toString method.
public BigNum(long n) {
int number = (int)n;
int[] tempNum = new int[MAX_DIGITS];
int counter=0;
while(number>0) {
tempNum[counter] = number % 10;
number /= 10;
counter++;
}
this.num = Arrays.copyOfRange(tempNum, 0, counter);
}
public String toString(){
String toReturn = "";
if(this.num.length>=1 && this.num.length<=3) {
for(int i=this.num.length-1 ; i>=0 ; i--) {
toReturn += num[i];
}
}else {
int commaPos = this.num.length%3==0?3:this.num.length%3;
int counter=0;
while(counter<this.num.length) {
if(counter==commaPos) {
toReturn+=",";
commaPos+=3;
}
toReturn+=num[this.num.length-1-counter]
counter++;
}
}
return toReturn;
}
I tested the above using the following code:
public static void main(String[] args) {
BigNum bn = new BigNum(1234567);
System.out.println(bn);
}
Output: 1,234,567

String compression algorithm in Java

I am looking to implement a method to perform basic string compression in the form of:
aabcccccaaa -> a2b1c5a3
I have this program:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
System.out.println(compress(str));
}
public static String compress(String str) {
char[] chars = str.toCharArray();
int count = 0;
String result = "";
for (int i = 0; i < chars.length; i++) {
char curr = chars[i];
result += curr;
for (int j = i; j < chars.length; j++) {
if (chars[j] == curr) {
count++;
}
else {
i += count;
break;
}
}
result += count;
count = 0;
}
return result;
}
}
But in my tests I am always missing the last character count.
I assume this is because the program gets out of the inner for loop before it should, but why is this the case?
Thanks a lot
You don't need two for loops for this and can do it in one go like so
String str = "aaabbbbccccca";
char[] chars = str.toCharArray();
char currentChar = str.length() > 0 ? chars[0] : ' ';
char prevChar = ' ';
int count = 1;
StringBuilder finalString = new StringBuilder();
if(str.length() > 0)
for(int i = 1; i < chars.length; i++)
{
if(currentChar == chars[i])
{
count++;
}else{
finalString.append(currentChar + "" + count);
prevChar = currentChar;
currentChar = chars[i];
count = 1;
}
}
if(str.length() > 0 && prevChar != currentChar)
finalString.append(currentChar + "" + count);
System.out.println(finalString.toString());
Output is: a3b4c5a1 for aaabbbbccccca
Keep a track of character that you are reading and compare it with next character of the string. If it is different, reset the count.
public static void stringCompression (String compression) {
String finalCompressedString = "";
char current = '1';
int count = 0;
compression = compression + '1';
for (int i = 0; i < compression.length(); i++) {
if (compression.charAt(i) == current) {
count = count + 1;
} else {
if (current != '1')
finalCompressedString = finalCompressedString + (current + Integer.toString(count));
count = 1;
current = compression.charAt(i);
}
}
System.out.println(finalCompressedString);
}
My answer for String Compression in java.
In this what i have done is and what you should have done is that , Keep a record of the characters that that are coming for a specific number of times, do so by comparing the current character with the next character , and when the current and the next character become unequal reset the value of count and repeat the whole process again for the next different character.
Hope it helps!
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
int count = 0;
for (int i=0; i<str.length(); ++i) {
int j=i+1;
count=1;
while (j!=str.length() && str.charAt(i) == str.charAt(j)) {
count += 1;
j += 1;
i += 1;
}
System.out.print(str.charAt(i));
if (count > 1) {
System.out.print(count);
}
}
}
}

Custom String split method in java

I am trying to implement a custom split string method and I am getting lost in for loops. I will post my code so far and hopefully someone can tell me where I am going wrong. I know there are better ways to do this, but I am just wondering why I can't seem to get the for loops to read properly. Basically I want to be able to set multiple delimiters at once. So I was populating a an array of just the delimiters and trying to compare each character in the full string with each entry in the delimiter Array. If it was not a delimiter, it added it to a string, if it was, it broke off the loop and took the string it created and added it to the first entry in the string array. This should continue until the character array was done.
Here is my code:
String[] charArray = new String[s.length()];
String[] stringArray = new String[s.length()];
String[] delimArray = new String[regex.length()];
// Fill array with delimiter values
for (int i=0; i < delimArray.length; i++) {
delimArray[i] = Character.toString(regex.charAt(i));
}
// Fill array with all values in string by character
for (int i=0; i < charArray.length; i++) {
charArray[i] = Character.toString(s.charAt(i));
}
for (int i=0; i < stringArray.length; i++) {
String s1 = "";
for (int k=0; k < charArray.length; k++) {
for (int j=0; j < delimArray.length; j++) {
if (charArray[k] != delimArray[j]) {
s1 = s1 + charArray[k];
} else if (charArray[k] == delimArray[j]) {
stringArray[i+1] = delimArray[j];
break;
}
}
s1 = s1 + charArray[k];
}
stringArray[i] = s1;
}
Try this-
public static String[] split(String string, String delem) {
ArrayList<String> list = new ArrayList<String>();
char[] charArr = string.toCharArray();
char[] delemArr = delem.toCharArray();
int counter = 0;
for (int i = 0; i < charArr.length; i++) {
int k = 0;
for (int j = 0; j < delemArr.length; j++) {
if (charArr[i+j] == delemArr[j]) {
k++;
} else {
break;
}
}
if (k == delemArr.length) {
String s = "";
while (counter < i ) {
s += charArr[counter];
counter++;
}
counter = i = i + k;
list.add(s);
//System.out.println(" k = "+k+" i= "+i);
}
}
String s = "";
if (counter < charArr.length) {
while (counter < charArr.length) {
s += charArr[counter];
counter++;
}
list.add(s);
}
return list.toArray(new String[list.size()]);
}
Try this:-
String regex = "";
String[] charArray = new String[s.length()];
String[] stringArray = new String[s.length()];
char[] delimArray = new char[regex.length()];
// Not required as you can directly use regex.charAt(i)
// Fill array with delimiter values
/*for (int i=0; i < delimArray.length; i++) {
delimArray[i] = regex.charAt(i);
}
*/
// Not required as you can directly use s.charAt(i)
// Fill array with all values in string by character
/*for (int i=0; i < charArray.length; i++) {
charArray[i] = Character.toString(s.charAt(i));
}*/
int i = 0;
// Outer loop
outer:
for (int k=0; k < s.length(); k++) {
// Inner loop
inner :
for (int j=0; j < delimArray.length; j++) {
// The if checks the current character in the string with each delimiter character and proceeds till it checks all the delimiters
if (s.charAt(k) != regex.charAt(j)) {
continue inner;
} else {
// If the current character is a delimiter then donot add it to the final string array result
i++;
continue outer;
}
}
// This if is to avoid null being appended to the string
if(stringArray[i] == null) {
stringArray[i] = "";
}
// Add the character(since it is not a delimiter) to the current index i
stringArray[i] += Character.toString(s.charAt(k));
}
//}
EDITED ANSWER:-
String s = "ab#12#45-3";
System.out.println(s.matches("\\d+"));
String regex = "-#";
String[] charArray = new String[s.length()];
String[] stringArray = new String[s.length()];
char[] delimArray = new char[regex.length()];
// Not required as you can directly use regex.charAt(i)
// Fill array with delimiter values
/*for (int i=0; i < delimArray.length; i++) {
delimArray[i] = regex.charAt(i);
}
*/
// Not required as you can directly use s.charAt(i)
// Fill array with all values in string by character
/*for (int i=0; i < charArray.length; i++) {
charArray[i] = Character.toString(s.charAt(i));
}*/
int i = 0;
// Outer loop
outer:
for (int k=0; k < s.length(); k++) {
// Inner loop
inner :
for (int j=0; j < delimArray.length; j++) {
// The if checks the current character in the string with each delimiter character and proceeds till it checks all the delimiters
if (s.charAt(k) != regex.charAt(j)) {
continue inner;
} else {
// Else block is reached when any of the character in the string is a delimiter
// Check if the current array position is null(which means nothing is assigned so far) and move to the next position only if it is not null
if(stringArray[i] != null) {
i++;
}
// Assign the delimiter in the output array
stringArray[i] = Character.toString(s.charAt(k));
// Increment to the next position in the array
i++;
continue outer;
}
}
// This if is to avoid null being appended to the string
if(stringArray[i] == null) {
stringArray[i] = "";
}
// Add the character(since it is not a delimiter) to the current index i
stringArray[i] += Character.toString(s.charAt(k));
}
//}
/*
* To avoid nulls in the final split array we need to initialize one more array
* and assign only valid values to the final split array
*/
String[] splitStrArr = new String[i+1];
int m = 0;
do {
splitStrArr[m] = stringArray[m];
m++;
} while (m <= i);

Java multidimensional Array to string and String to Array

I have array
data[][];
convert to string:
string = Arrays.deepToString(data);
string:
[[1, 1394119227787, 59474093, USD/DKK, true, 0.05, 5.391582, 5.00663, 5.39663, null, null], [1, 1394581174413, 59500543, EUR/JPY, false, 0.05, 142.489381, 145.3, 139.68, null, null],
[1, 1394581174413, 59500543, EUR/JPY, false, 0.05, 142.489381, 145.3, 139.68, null, null],
[1, 1394581174413, 59500543, EUR/JPY, false, 0.05, 142.489381, 145.3, 139.68, null, null]]
and How convert this string back to array?
Try my stringToDeep() method to convert back to Array.
import java.util.*;
public class DeepToArray {
public static void main(String[] args) {
int row, col;
row = 2;
col = 3;
String[][] in = new String[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
in[i][j] = i + " " + j;
}
}
String str = Arrays.deepToString(in);
System.out.println(str);
String[][] out = stringToDeep(str);
for (String s2[] : out) {
for (String s3 : s2) {
System.out.print(s3 + " ");
}
System.out.println();
}
}
private static String[][] stringToDeep(String str) {
int row = 0;
int col = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == '[') {
row++;
}
}
row--;
for (int i = 0;; i++) {
if (str.charAt(i) == ',') {
col++;
}
if (str.charAt(i) == ']') {
break;
}
}
col++;
String[][] out = new String[row][col];
str = str.replaceAll("\\[", "").replaceAll("\\]", "");
String[] s1 = str.split(", ");
int j = -1;
for (int i = 0; i < s1.length; i++) {
if (i % col == 0) {
j++;
}
out[j][i % col] = s1[i];
//System.out.println(s1[i] + "\t" + j + "\t" + i % col);
}
return out;
}
}
There is no method in the java API that will automatically convert this back to an array. You could write code to do this yourself, but it would be tricky; this format does not escape special characters like the square brackets, or the commas. It might be easier just to use a format which is designed for encoding and decoding arrays, like JSON.
All the answers I found are 2-dimensional only, so here's my solution to reverse deepToString(...) for any number of dimensions:
Usage example:
String arrString = "[[[0.11695497071135137, 0.8830064157596283, 0.3433854446148375, 0.18825445694298526, 1.0441938749175883, 0.8941633746325311], [-0.089908138214512, 0.39821330927870574, 0.1365997500579524, 0.7008902956765364, 0.9897596683277262, 0.2847717055995359], [0.6450670283688857, 0.01516064860567864, -0.07904927386204857, 0.2703900981351612, 0.45402985012492075, 0.30505608337251183], [0.5122943117220898, 0.008726346575469023, 0.7734611917871235, 0.3051772999891666, 0.5237487372571624, 1.1824105144656751]]]";
String[][][] arr = (String[][][]) reverseDeepToString(arrString);
System.out.println(Arrays.deepToString(arr));
This code converts a string (arrString) into an array, and then the function Arrays.deepToString(...) converts it back into the same string.
Function code:
public static Object reverseDeepToString(String str){
int dimensions = 0;
for(int x = 0; x < str.length(); x++)
if(str.charAt(x) == '[')
dimensions++;
else break;
str = str.substring(dimensions, str.length() - dimensions);
return createArrayRecursive(str, dimensions);
}
private static Object createArrayRecursive(String str, int dimension){
if(dimension == 1)
return str.split(", "); // modify the code here if you want to convert the strings to another variable type
String[] s = str.split(getArraySeparator(dimension));
int[] lengths = new int[dimension];
lengths[0] = s.length;
Object arr = Array.newInstance(String.class, lengths); // and here (see comment above)
for(int x = 0; x < s.length; x++)
Array.set(arr, x, createArrayRecursive(s[x], dimension - 1));
return arr;
}
private static String getArraySeparator(int dimension){
String separator = ", ";
for(int x = 1; x < dimension; x++)
separator = ']' + separator + "\\[";
return separator;
}
Array to string and back to array :P
import java.util.Arrays;
import java.util.Random;
public class arrays {
public static void main(String [ ] args)
{
String[][] in = new String [10][4];
String[][] out = new String [10][4];
arrays nr = new arrays();
for(int i =0; i< 4; i++){
for(int j =0; j< 4; j++){
in[i][j] = nr.Rand(5);
}
}
System.out.println(Arrays.deepToString(in));
// tablica ok
// convert array to string
String line = "";
for(int i =0; i< 4; i++){
for(int j =0; j< 4; j++){
line += in[i][j] + "_";
}
line += ":";
}
System.out.println(line);
// line back to array
String[] xline = line.split(":");
int ss = 0;
for (String str : xline) {
out[ss] = (String[]) str.split("_");
System.out.println("string line>>>" + str);
ss++;
}
System.out.println(Arrays.deepToString(out));
}
public String nextSessionId() {
//private SecureRandom random = new SecureRandom();
//return new BigInteger(130, random).toString(32);
return null;
}
public String Rand(int zz){
char[] chars = "987654321abcdefghijklm111nopqrstuvwxyz0123456789".toCharArray();
StringBuilder sb = new StringBuilder();
Random random = new Random();
for (int i = 0; i < zz; i++) {
char c = chars[random.nextInt(chars.length)];
sb.append(c);
}
String output = sb.toString();
// System.out.println(output);
return output;
}
}
:D

Sort strings in an array based on length

I have the below program for sorting Strings based on length. I want to print the shortest element first. I don't want to use Comparator or any API to do this. Where I am going wrong?
public class SortArrayElements {
public static void main(String[] args) {
String[] arr = new String[]{"Fan","dexter","abc","fruit","apple","banana"};
String[] sortedArr = new String[arr.length];
for(int i=0;i<sortedArr.length;i++)
{
sortedArr[i] = compareArrayElements(arr);
}
System.out.println("The strings in the sorted order of length are: ");
for(String sortedArray:sortedArr)
{
System.out.println(sortedArray);
}
}
public static String compareArrayElements(String[] arr) {
String temp = null;
for(int i=0;i<arr.length-1;i++)
{
temp = new String();
if(arr[i].length() > arr[i+1].length())
temp = arr[i+1];
else
temp = arr[i];
}
return temp;
}
}
If you really want to learn Java: use a Comparator. Any other way is bad Java code.
You can however rewrite the Comparator system if you want, it will teach you about proper code structuring.
For your actual code, here are some hints:
Using the proper algorithm is much more important than the Language you use to code. Good algorithms are always the same, no matter the language.
Do never do new in loops, unless you actually need to create new objects. The GC says "thanks".
Change the compareArrayElements function to accept a minimum size and have it return the smallest String with at least minimum size.
You could cut out those Strings that you have considered to be the smallest (set them to null), this will however modify the original array.
Use bubble sort, but instead of comparing ints, just compare String lengths.
I won't write the code for you. You will have to do a little bit of research on this algorithm. Google is your best friend as a programmer.
Good luck.
References:
Bubble sort in Java
Sorting an array of strings
Implement bubbleSort() and swap(). My implementations mutate the original array, but you can modify them to make a copy if you want.
public class SortArrayElements {
public static void main(String[] args) {
String[] arr = new String[]{"Fan", "dexter", "abc", "fruit", "apple", "banana"};
bubbleSort(arr);
System.out.println("The strings in the sorted order of length are: ");
for (String item : arr) {
System.out.println(item);
}
}
// Mutates the original array
public static void bubbleSort(String[] arr) {
boolean swapped = false;
do {
swapped = false;
for (int i = 0; i < arr.length - 1; i += 1) {
if (arr[i].length() > arr[i + 1].length()) {
swap(arr, i, i + 1);
swapped = true;
}
}
} while (swapped);
}
// Mutates the original array
public static void swap(String[] arr, int index0, int index1) {
String temp = arr[index0];
arr[index0] = arr[index1];
arr[index1] = temp;
}
}
Okay, there is the code completely based on loops and on bubble sort. No sets are there as you wanted it. This is a pure loop program so you could understand the nested loops, plus it doesn't change the index or something of the string
import java.util.*;
class strings {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<String> a = new ArrayList<String>(2);
System.out.println("Start entering your words or sentences.");
System.out.println("Type stop to stop.");
String b;
int c = 0, d;
do {
b = in.nextLine();
b = b.trim();
a.add(b);
c++;
}
while (!b.equalsIgnoreCase("stop"));
if (c > 1)
a.remove(a.size() - 1);
System.out.println("Choose the sort you want. Type the corresponding
number");
System.out.println("1. Ascending");
System.out.println("2. Descending");
int sc=in.nextInt();
switch(sc) {
case 1: {
int sag[] = new int[a.size()];
for (int jk = 0; jk < a.size(); jk++) {
b = a.get(jk);
c = b.length();
sag[jk] = c;
}
int temp;
for (int i = 0; i < a.size() - 1; i++) {
for (int j = 0; j < a.size() - 1; j++) {
if (sag[j] > sag[j + 1]) {
temp = sag[j + 1];
sag[j + 1] = sag[j];
sag[j] = temp;
}
}
}
ArrayList saga = new ArrayList();
for (int i = 0; i < sag.length; i++) {
saga.add(sag[i]);
}
for (int i = 0; i < saga.size(); i++) {
for (int j = i + 1; j < saga.size(); j++) {
if (saga.get(i).equals(saga.get(j))) {
saga.remove(j);
j--;
}
}
}
for (int i = 0; i < saga.size(); i++) {
for (int j = 0; j < a.size(); j++) {
String jl = a.get(j);
if (saga.get(i).equals(jl.length()))
System.out.println(jl);
}
}
break;
}
case 2: {
int sag[] = new int[a.size()];
for (int jk = 0; jk < a.size(); jk++) {
b = a.get(jk);
c = b.length();
sag[jk] = c;
}
int temp;
for (int i = 0; i < a.size() - 1; i++) {
for (int j = 0; j < a.size() - 1; j++) {
if (sag[j] < sag[j + 1]) {
temp = sag[j + 1];
sag[j + 1] = sag[j];
sag[j] = temp;
}
}
}
ArrayList saga = new ArrayList();
for (int i = 0; i < sag.length; i++) {
saga.add(sag[i]);
}
for (int i = 0; i < saga.size(); i++) {
for (int j = i + 1; j < saga.size(); j++) {
if (saga.get(i).equals(saga.get(j))) {
saga.remove(j);
j--;
}
}
}
for (int i = 0; i < saga.size(); i++) {
for (int j = 0; j < a.size(); j++) {
String jl = a.get(j);
if (saga.get(i).equals(jl.length()))
System.out.println(jl);
}
}
break;
}
}
}
}
For instance, the following:
ArrayList<String> str = new ArrayList<>(
Arrays.asList(
"Long", "Short", "VeryLong", "S")
);
By lambda:
str.sort((String s1, String s2) -> s1.length() - s2.length());
By static Collections.sort
import static java.util.Collections.sort;
sort(str, new Comparator<String>{
#Override
public int compare(String s1, String s2) {
return s1.lenght() - s2.lenght()
}
});
Both options are implemented by default sort method from List interface
Let's take a following array of String inputArray = ["abc","","aaa","a","zz"]
we can use Comparator for sorting the given string array to sort it based on length with the following code:
String[] sortByLength(String[] inputArray) {
Arrays.sort(inputArray, new Comparator<String>(){
public int compare(String s1, String s2){
return s1.length() - s2.length();
}
});
return inputArray;
}
//sort String array based on length
public class FirstNonRepeatedString {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please Enter your String");
String str = in.nextLine();
String arrString[] = str.split("\\s");
arrString = sortArray(arrString);
System.out.println("Sort String ");
for(String s:arrString){
System.out.println(s);
}
}
private static String[] sortArray(String[] arrString) {
int length = arrString.length;
String s;
for (int i = 0; i < length ; i++) {
s= new String();
for(int j = 0; j < length; j++ ){
if(arrString[i].length()< arrString[j].length()){
s = arrString[i];
arrString[i] = arrString[j];
arrString[j] = s;
}
}
}
return arrString;
}
}
import java.util.*;
public class SortStringBasedOnTheirLength {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter String:");
String str=sc.nextLine();
String[] str1=str.split("\\s");
for(int i=0;i<str1.length;i++)
{
for(int j=i+1;j<str1.length;j++)
{
if(str1[i].length()>str1[j].length())
{
String temp= str1[i];
str1[i]=str1[j];
str1[j]=temp;
}
}
}
for(int i=0;i<str1.length;i++)
{
System.out.print(str1[i]+" ");
}
}
}

Categories

Resources