java one dimensional string to multidimensional - java

I am given a string that can represent hex values and am told to convert it to such and store it in a string:
String str = new String("FF E7 C3 E7 FF");
String[] arrayStr = str.split(" ");
Then I need to convert each hex value to its binary equivalent:
String[] arrayBin = new String[arrayStr.length];
for (int i = 0; i < arrayStr.length; i++) {
arrayBin[i] = Integer.toBinaryString(Integer.parseInt(arrayStr[i],16));
}
This is where I get lost. Is this binary string technically one dimensional or two dimensional? Basically, I need to convert it to a two dimensional array so that I can iterate through it in both x and y directions, to perform something like this:
for (int k = 0; k < arrayBin.length; k++) {
for (int l = 0; l < arrayBin[k].length; l++) {
if (arrayBin[k][l] == "1") {
arrayBin[k][l] = "x";
} else {
arrayBin[k][l] = " ";
}
}
}
At this point I get nothing but compiler errors, and despite all the articles online about multidimensional arrays, no search has given me something that works. I have tried things like:
String[][] arrayBin2 = new String[arrayBin.length][]
for (int m = 0; m < arrayBin.length; m++) {
arrayBin2[m][] = arrayBin[m];
}
But that did not work. Any help or suggestions as to what I am doing wrong would be greatly appreciated.
Second attempt in response to #Eran 's suggestions:
public class Challenge3 {
public static void main(String args[]) {
String str = new String("FF E7 C3 E7 FF");
String[] arrayStr = str.split(" ");
String[] arrayBin = new String[arrayStr.length];
for (int i = 0; i < arrayStr.length; i++) {
arrayBin[i] = Integer.toBinaryString(Integer.parseInt(arrayStr[i],16));
}
for (int k = 0; k < arrayBin.length; k++) {
StringBuilder sb = new StringBuilder(arrayBin[k].length());
for (int l = 0; l < arrayBin[k].length(); l++) {
if (arrayBin[k].charAt(l) == 1) {
sb.append("x");
} else {
sb.append(" ");
}
}
arrayBin[k] = sb.toString();
System.out.println(arrayBin);
}
}
}
As a side note, the code is supposed to print out the following when done correctly:
xxxxxxxx
xxx xxx
xx xx
xxx xxx
xxxxxxxx

Your arrayBin is 1-dimentional.
If you want to iterate over the bits of each binary String, use the methods length() and charAt() of the String class :
for (int k = 0; k < arrayBin.length; k++) {
StringBuilder sb = new StringBuilder(arrayBin[k].length());
for (int l = 0; l < arrayBin[k].length(); l++) {
if (arrayBin[k].charAt(l) == '1') {
sb.append ('x');
} else {
sb.append (' ');
}
}
arrayBin[k] = sb.toString();
System.out.println(arrayBin[k]);
}
Output :
xxxxxxxx
xxx xxx
xx xx
xxx xxx
xxxxxxxx
Note that you can't change the String instances in your arrayBin array, since String is immutable. What you can do is construct a new String and replace each String in the arrayBin array with the new String.

Related

I'm not able to sort the splited strings properly using comparedTo method. What can I do to correct it?

This is my code, but I know this is not right. I have written a lot of code for such a simple task.
Sample input is:
welcome
Sample output is:
com
elc
lco
ome
wel
It should print:
your first string is 'com'
and
your last string is 'wel'
Code:
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
int k = sc.nextInt();
int k1 = k;
int j = 0;
int t = str.length();
String [] s = new String [1000];
for (int i = t, a = 0; i >= k; i--, a++) {
s[a] = str.substring(j, k1);
j++;
k1++;
}
String[] s1 = new String[j];
for (int i = 0 ; i < j; i++) {
s1[i] = s[i];
}
for (int y = 0; y < j; y++) {
for (int z = y + 1; z < j; z++) {
if(s1[z].compareTo(s1[y]) < 0) {
String temp = s1[z];
s1[z] = s1[y];
s1[y] = temp;
}
}
}
System.out.println(s1[0]);
System.out.println(s1[1]);
}
}
Note: I split my strings, but I'm not able to arrange strings in alphabetical order, and feel that I have used a lot of arrays. Is there a better way to do this?
You can
reduce the number of variables,
use collections (list in this case) instead of Arrays to avoid having to set a size (1000)
Sort using the framework
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
int k = sc.nextInt();
List<String> cutStrings = new ArrayList<String>();
for (int i = 0; i < str.length() - k; i++) {
cutStrings.add(str.substring(i, i + k));
}
Collections.sort(cutStrings);
System.out.println(cutStrings.get(0));
System.out.println(cutStrings.get(cutStrings.size()-1));
}
You can easily sort your String[] array by simply using
Arrays.sort(s);
This will sort your strings in the default order. If you need any other kind of order you can pass the comparator as a second parameter.
You can get first and last by getting s[0] and s[s.length-1]
I did a quick implementation of your requirements. It might not be exactly what you're looking for but it should get you started. :)
So, I used an ArrayList to grab the substrings and the use the Collections library to do the sorting for me. This is just one of the many ways of solving the problem, btw. The input word can vary in size so I felt that a list would be appropriate for this situation.
String s = "welcome";
List<String> words = new ArrayList<String>();
for (int i = 0; i < s.length() - 2; i++) {
String chunk = s.charAt(i) + "" + s.charAt(i + 1) + ""
+ s.charAt(i + 2);
words.add(chunk);
System.out.println(chunk);
}
Collections.sort(words);
System.out.println(words.toString());
Feel free to let me know if you have any questions or if I have made a mistake in the code.
Good luck!
Actual problem of your code is splitting. Sorting will work. If j value 1 and k1 value 3 then wel substring is coming. Next loop, (after incrementation of both j and k1 by 1) j value 2 and k1 value 4 then elc substring is coming, etc.
So, instead of
String [] s = new String [1000];
for (int i = t, a = 0; i >= k; i--, a++) {
s[a] = str.substring(j, k1);
j++;
k1++;
}
use
int k = sc.nextInt();
String [] s = new String [(str.length()/3)+1] ;
for ( int i = 0,a = 0; i<(str.length()-k); i+=k,a++)
{
s[a] = str.substring(i,(i+k));
System.out.println(s[a]);
}
s[s.length-1]=str.substring((str.length()-k),str.length());//to add remaining values
Arrays.sort(s);//sorting alphabatically
for(int i = 0; i < s.length; i++)
System.out.println(s[i]);
}
i value will be incremented by 3. In the for loop (i+=k) where k=3.
Output:
amp
com
e s
ple
wel

Finding the middle letter and make it uppercase.. am stuck and the end .. :(

Here am finding the middle letter of each element of the array and making it upper case and merge it so that it'll give me a result like e:g- {bOy, inDia, apPle}
Following is the code am trying till now.
public class FindMiddle {
public static void main(String[] args) {
ArrayList<String> al = new ArrayList<String>();
al.add("boy india apple");
String str[] = al.toArray(new String[al.size()]);
String newar[];
String delimiter = " ";
newar = str[0].split(delimiter);
for (int i = 0; i < newar.length; i++) {
char[] c = newar[i].toCharArray();
for (int j = 0; j < c.length; j++) {
if (j == c.length / 2) {
c[j] = Character.toUpperCase(c[c.length / 2]);
System.out.println(c[j]);
}
newar[i] += c[j];
}
}
}
}
It's only giving me O D P.
I want them merged with the original elements like bOy inDia apPle.
that's because you print only the middle char (the println is inside the if statement)
if (j == c.length / 2) {
c[j] = Character.toUpperCase(c[c.length / 2]);
System.out.println(c[j]);
}
I would suggest using StringBuilder.setCharAt
for (int i = 0; i < newar.length; i++) {
StringBuilder updateString = new StringBuilder(newar[i]);
int middleIndex = newar[i].length /2;
updateString.setCharAt(middleIndex, Character.toUpperCase(newar[i].charAt(middleIndex));
System.out.println(updateString);
}
you could use the charAt function of the String object and replace function
using the full String.length is not accurate when you will be accessing the middle index of the String since index are length - 1 (because it starts with 0) so you need to deduct 1 from the length and then divide it by half.
for(int i=0;i<newar.length;i++){
int index = (newar[i].length()-1)/2;
newar[i] = newar[i].replace(newar[i].charAt(index), Character.toUpperCase(newar[i].charAt(index)));
System.out.println(newar[i]);
}
output:
bOy
inDia
aPPle
Try this :
for (int i = 0; i < newar.length; i++) {
char[] c = newar[i].toCharArray();
for (int j = 0; j < c.length; j++) {
if (j == c.length / 2) {
c[j] = Character.toUpperCase(c[c.length / 2]);
//System.out.print(c[j]); <--- you keep getting O D P because you
print them here
}
// newar[i] += c[j]; <-- here you just concat changed elements to newar
System.out.print(c[j]); <--- print the value of array none middle and middle one
}
if (i != newar.length-1) { <-- avoid printing , for last item
System.out.print(",");
}
}
output:
bOy,inDia,apPle
My explanations are as comment inside the code.
Note: when you are in a for loop, you are checking whether you ecnounter the middle character. if you encountered, you will make it uppercase other wise nothing is changed, and each character is printed out on the console.
import java.util.ArrayList;
public class Test
{
public static void main(String[] args) {
ArrayList<String> al = new ArrayList<String>();
al.add("boy india apple");
String str[] = al.toArray(new String[al.size()]);
String newar[];
String delimiter = " ";
newar = str[0].split(delimiter);
for (int i = 0; i < newar.length; i++) {
char[] c = newar[i].toCharArray();
for (int j = 0; j < c.length; j++) {
if (j == c.length / 2) {
c[j] = Character.toUpperCase(c[c.length / 2]);
// System.out.println(c[j]);
// (1)
}
System.out.print(c[j]);
// (2)
newar[i] += c[j];
}
System.out.println();
// (3)
}
}
}
(1) - I got rid of this because it would only print out the uppercase letter. You had set the middle characters in all 3 words to uppercase, but, you need to print out the whole word, not just one letter.
(2) - You do, however, want to print out the whole word, which is what this line is doing. Instead of doing println, it only does print. Reason is because we are taking advantage of that for loop that is going through each character in the specific word to be able to print out each letter after we are done checking if it's the middle letter.
(3) - We have this line here because we want to be able to separate between words. I am not sure how you want these words separated so change this as you feel it's necessary, I just separated them so you could see.
There are a lot of things wrong with your code, so here is a simplified rewrite:
public static void main(String[] args) {
String s = "boy india apple";
String[] split = s.split( " " );
String[] toReturn = new String[split.length];
for (int i = 0; i < split.length;i++)
{
String word = split[i];
char[] chars = word.toCharArray();
chars[chars.length/2] = Character.toUpperCase( chars[chars.length/2] );
toReturn[i] = String.valueOf( chars );
}
System.out.println(Arrays.toString( toReturn ));
}
In order to correct your code you can start by removing the useless ArrayList and moving the System.out outside of the for loop. There are some other issues like you are appending the new result to the original so newar after this runs will look like {boybOy, indiainDia, appleapPle}.
EDIT:
For teaching purposes, here is your code modified so that it will work; however inefficient.
public static void main(String[] args) {
ArrayList<String> al = new ArrayList<String>();
al.add("boy india apple");
String str[] = al.toArray(new String[al.size()]);
String newar[];
String delimiter = " ";
newar = str[0].split(delimiter);
System.out.print("{");
for (int i = 0; i < newar.length; i++) {
char[] c = newar[i].toCharArray();
for (int j = 0; j < c.length; j++) {
if (j == c.length / 2) {
c[j] = Character.toUpperCase(c[c.length / 2]);
}
System.out.print(c[j]);
}
newar[i] = String.valueOf(c);
if (i < newar.length - 1)
System.out.print(",");
}
System.out.println("}");
}
String temp = ""; //define temp string as "" (don't assign null)
for (int j = 0; j < c.length; j++) {
...
//newar[i] += c[j]; //don't append to existing String in array
temp += c[j];
newar[i] = temp;
}
//after replacement is done
//now can print replaced string in array by looping
for (String string : newar) {
System.out.println(string);
}

How to convert a String array to char array in Java

We are given an array of Strings and what we require is a char[], i.e, array of all characters in all the Strings
For example:
Input: [i, love, you]
output: [i, l, o, v, e, y, o, u]
First I made an array of arrays.
Then I have found the length of the required char[] array.
I have tried the following so far:
char[][] a1 = new char[str.length][];
for(int i =0;i<str.length;i++){
a1[i]=str[i].toCharArray();
}
int total=0;
for(int i =0;i<str.length;i++){
total = total + a1[i].length;
}
char[] allchar = new char[total];
for(int i=0;i<str.length;i++){
//NOW HERE I WANT TO MERGE ALL THE char[] ARRAYS TOGETHER.
//HOW SHOULD I DO THIS?
}
String[] sArray = {"i", "love", "you"};
String s = "";
for (String n:sArray)
s+= n;
char[] c = s.toCharArray();
You can do that like this
char[] allchar = new char[total]; // Your code till here is proper
// Copying the contents of the 2d array to a new 1d array
int counter = 0; // Counter as the index of your allChar array
for (int i = 0; i < a1.length; i++) {
for (int j = 0; j < a1[i].length; j++) { // nested for loop - typical 2d array format
allchar[counter++] = a1[i][j]; // copying it to the new array
}
}
You can do something like the following method..
public void converter(String[] stringArray) {
char[] charsInArray = new char[500]; //set size of char array
int counterChars = 0;
for (int i = 0; i < stringArray.length; i++) {
int counterLetters = 0; //declare counter for for amount of letters in each string in the array
for (int j = 0; j < stringArray[i].length(); j++) {
// below pretty self explanatory extracting individual strings and a
charsInArray[counterChars] = stringArray[i].charAt(counterLetters);
counterLetters++;
counterChars++;
}
}
}
String [] s = new String[]{"i", "love", "you"};
int length = 0;
for (int i = 0; i < s.length; i++) {
for (int j = 0; j < s[i].length(); j++) {
length++;
}
}
char [] c = new char[length];
int k = 0;
for (int i = 0; i < s.length; i++) {
for (int j = 0; j < s[i].length(); j++) {
c[k] = s[i].charAt(j);
k++;
}
}
for (int j = 0; j < c.length; j++) {
System.out.print("char is: " + c[j]);
}
In Java 8 we can use streams.
public char[] convert(String[] words) {
return Arrays.stream(words)
.collect(Collectors.joining())
.toCharArray();
}
Here we created a stream from an array using
Array.stream(T[] array) where T is the type of the array elements.
Than we obtain a string using Collectors.joining(). Finally we get a char array using the String's toCharArray() method.
public static void main(String[] args)
{
String sentence="Gokul Krishna is class leader";
String[] array=sentence.split("\\s");
int counter;
//String word = new String();
for(String word:array)
{
counter=0;
char[] wordArray=word.toCharArray();
for(int i=0;i<wordArray.length;i++)
{
counter++;
}
System.out.println(word+ " :" +counter);
}
}
public char[] convert(String[] arr) {
StringBuilder sb = new StringBuilder();
for (String s : arr) {
sb.append(s);
}
return sb.toString().toCharArray();
}

subString combined with the practices of the for loop

I get a long list of strings from the server
AS= String1 ~ String2 ~ String3 ~
Can be determined.
"~"Represents the end of each data.
I know that the word limit for each String of up to 22
But I do not know his actual length.
So I use this code to determine the value of each String
//////////////////////////Use of substring Get every character
String T1=AS.substring(0,1);
String T2=AS.substring(1,2);
.
.
.
String T22=AS.substring(21,22);
if (T2.equals("~")) {
DATA=T1;
}
if (T3.equals("~")) {
DATA=T1+T2;
}
//Confirm T3 "~" Get DATA = T2 + T1
String LG=LG+DATA.length()+1;
//The second document must be added to the number of words in the document "~"
String TT1=AS.substring(0+LG,1+LG);
Determine string of 100
Repeat 100 times
I have manufactured more than 8,000 lines of code
There is no easier way to reach my request?
Just a little bit to help you out.
String[] TKG = new String[GUY.length];
for (int i = 0; i < GUY.length - 1; i++)
{
TKG[i] = GUY.substring(i, i+1);
}
and then
StringBuilder DETA5 = new StringBuilder();
for (int i = 1; i < TKG.length; i++)
{
if (TKG[i].equals("~"))
{
for (int x = 0; x < i; x++)
{
DETA5.append(TKG[x]);
}
}
}
int D = D + DETA5.length();
String[] TKC = new String[6];
for (int i = 0; i < 6; i++)
{
TKC[i] = GUY.substring(i+D1, i + 1 + D1);
}
StringBuilder DETA_1_1 = new StringBuilder();
for (int i = 1; i < TKC.length; i++)
{
if (TKC[i].equals("~"))
{
for (int x = 0; x < i; x++)
{
DETA_1_1.append(TKC[x]);
}
}
}
Good Luck!
It looks almost as if a simple String#split(...) will do the trick for you. Have you tried something along the lines of
String[] tokens = guy.split("~");
Perhaps after a little cleaning up of the edge Strings, you'll have what you want.

How to print two dimensional array of strings as String

I know how to do the toString method for one dimensional arrays of strings, but how do I print a two dimensional array? With 1D I do it this way:
public String toString() {
StringBuffer result = new StringBuffer();
res = this.magnitude;
String separator = "";
if (res.length > 0) {
result.append(res[0]);
for (int i=1; i<res.length; i++) {
result.append(separator);
result.append(res[i]);
}
}
return result.toString();
How can I print a 2D array?
The Arrays class defines a couple of useful methods
Arrays.toString - which doesn't work for nested arrays
Arrays.deepToString - which does exactly what you want
String[][] aastr = {{"hello", "world"},{"Goodbye", "planet"}};
System.out.println(Arrays.deepToString(aastr));
Gives
[[hello, world], [Goodbye, planet]]
You just iterate twice over the elements:
StringBuffer results = new StringBuffer();
String separator = ","
float[][] values = new float[50][50];
// init values
for (int i = 0; i < values.length; ++i)
{
result.append('[');
for (int j = 0; j < values[i].length; ++j)
if (j > 0)
result.append(values[i][j]);
else
result.append(values[i][j]).append(separator);
result.append(']');
}
IMPORTANT: StringBuffer are also useful because you can chain operations, eg: buffer.append(..).append(..).append(..) since it returns a reference to self! Use synctactic sugar when available..
IMPORTANT2: since in this case you plan to append many things to the StringBuffer it's good to estimate a capacity to avoid allocating and relocating the array many times during appends, you can do it calculating the size of the multi dimensional array multiplied by the average character length of the element you plan to append.
public static <T> String to2DString(T[][] x) {
final String vSep = "\n";
final String hSep = ", ";
final StringBuilder sb = new StringBuilder();
if(x != null)
for(int i = 0; i < x.length; i++) {
final T[] a = x[i];
if(i > 0) {
sb.append(vSep);
}
if(a != null)
for(int j = 0; j < a.length; j++) {
final T b = a[j];
if(j > 0) {
sb.append(hSep);
}
sb.append(b);
}
}
return sb.toString();
}
Two for loops:
for (int i=1; i<res.length; i++) {
for (int j=1; j<res[i].length; j++) {
result.append(separator);
result.append(res[i][j]);
}
}
public static void main(String[] args) {
String array [] [] = {
{"*","*", "*", "*", "*", "*"},
{"*"},
{"*"},
{"*"},
{"*","*", "*", "*", "*", "*"},
{"*"},
{"*"},
{"*"},
{"*"},
{"*"}};
for (int row=0; row<array.length;row++) {
for (int column = 0; column < array[row].length; column++) {
System.out.print(array[row][column]);
}
System.out.println();
}
}

Categories

Resources