split into arrays from a string array - java

I am using Java 1.4 for an old project.
I have a string array
String a[0]={"200,300"}
String a[1]={"700,500"}
String a[2]={"900,400"}
as so on,
for this I need to create 2 string array to get the first value in a string array and second value in different string array.
ex:
String a[0]="200"
String a[1]="700"
String a[2]="900"
String b[0]="300"
String b[1]="500"
String b[2]="400"
I am not getting how can I do this.

If the length of the string array is known,
String[] newString = new String [6];
int count = 0;
for(int i = 0; i<3 ; i++){
newString[i] = a[i];
count++;
}
for(int j=0; j<3; j++){
newString[count] = b[j];
count++;
}
EDIT:
Previously i got your question wrong. The following solution will help you. to divide a into 2 string arrays.
String a[] = new String [3];
a[0]={"200,300"};
a[1]={"700,500"};
a[2]={"900,400"};
String[] newStr1 = new String [a.length];
String[] newStr2 = new String [a.length];
for(int i = 0; i<3 ; i++){
String [] x= a[i].split(",");
newStr1[i] = x[0];
newStr2[i] = x[1];
}

Looking at your code, this provides you the correct solution,
int n = 3; //This can change as your array size is not known
String a[] = new String [n];
a[0]="200,300";
a[1]="700,500";
a[2]="900,400"; //And So on
String[] b1 = new String [n];
String[] b2 = new String [n];
for(int i = 0; i<n ; i++)
{
String [] numbers= a[i].split(",");
b1[i] = numbers[0];
b2[i] = numbers[1];
}

First you cant defined String array as string a[1]={700,500}. It is wrong way.
And second, Here is what you want :
a[0]=new String[]{"200","300"};
a[1]=new String[]{"700","500"};
a[2]=new String[]{"900","400"};
String x[] = new String[a.length];
String y[] = new String[a.length];
for(int i=0;i<a.length;i++){
x[i] = a[i][0];
y[i] = a[i][1];
}

Related

how to create a string from char array by adding char by char in java

How to create a String in Java by adding char by char.
I have to do it like this, because i have to add a "," between al letters.
I tried it like this, but it had not worked.
String t;
int l = t.length();
char[] a;
a = new char[l];
String rel = ",";
String ret = null;
for (int i = 0; i<l; i++){
a[i] = new Character(t.charAt(0));
}
for (int v = 0; v<l; v--){
ret += a[v];
ret += rel;
}
You don't need to do it so complicated, and you should explicitly use StringBuilder for such string operations:
String s = "abcdefg";
StringBuilder builder = new StringBuilder();
for (char c : s.toCharArray()) {
builder.append(c).append(",");
}
// Alternatively, you can do it in this way
for (String symbol : s.split("")) {
builder.append(symbol).append(",");
}
System.out.println(builder.toString());
// Java 8 (the result string doesn't have a comma at the end)
String collect = Arrays.stream(s.split("")).collect(Collectors.joining(","));
// Java8 StringJoiner
StringJoiner sj = new StringJoiner(",");
// StringJoiner sj = new StringJoiner(",", "", ",");
for (String str : s.split("")) {
sj.add(str);
}
If you use empty strings instead of null and initialize it then it works.
String t = "foobarbaz";
int l = t.length();
char[] a;
a = new char[l];
String rel = ",";
String ret = "";
for (int i = 0; i<l; i++){
a[i] = t.charAt(i);
}
for (int v = 0; v<l; v++){
ret += a[v];
ret += rel;
}
System.out.println(ret);
I've put the errors in your code in comments.
String t;
int l = t.length();
char[] a;
a = new char[l];
String rel = ",";
String ret = null; //you initialize ret to null, it should be "";
for (int i = 0; i<l; i++){
//you always set it to the character at position 0, you should do t.charAt(i)
//you don't need to use the wrapper class just t.charAt(i) will be fine.
a[i] = new Character(t.charAt(0));
}
for (int v = 0; v<l; v--){//you decrement v instead of incrementing it, this will lead to exceptions
ret += a[v];
ret += rel;//you always add the delimiter, note that this will lead to a trailing delimiter at the end
}
You might want to try a StringBuilder. It's a lot more efficient than using string concatenation. Using the array a is also not really necessary. Have a look at this implementation.
String t = "Test";
StringBuilder builder = new StringBuilder();
if(t.length() > 0){
builder.append(t.charAt(0));
for(int i=1;i<t.length();i++){
builder.append(",");
builder.append(t.charAt(i));
}
}
System.out.println(builder.toString());
Take a look at this:
//Word to be delimited by commas
String t = "ThisIsATest";
//get length of word.
int l = t.length(); //4
char[] a;
a = new char[l];
// we will set this to a comma below inside the loop
String rel = "";
//set ret to empty string instead of null otherwise the word "null" gets put at the front of your return string
String ret = "";
for (int i = 0; i<l; i++){
//you had 0 instead of 'i' as the parameter of t.charAt. You need to iterate through the elements of the string as well
a[i] = new Character(t.charAt(i));
}
for (int v = 0; v<l; v++){
/*set rel to empty string so that you can add it BEFORE the first element of the array and then afterwards change it to a comma
this prevents you from having an extra comma at the end of your list. */
ret += rel;
ret += a[v];
rel = ",";
}
System.out.println(ret);
String text = "mydata";
char[] arrayText = text.toCharArray();
char[] arrayNew = new char[arrayText.length*2];
for(int i = 0, j = 0; i < arrayText.length; i++, j+=2){
arrayNew[j] = arrayText[i];
arrayNew[j+1] = ',';
}
String stringArray = new String(arrayNew);
System.out.println(stringArray);
Results
m,y,d,a,t,a,

Convert comma separated string to array without string split?

Using Java, how would I convert "Paul, John, Ringo" to
Paul
John
Ringo
But while using a loop that searches for the commas and pulls out the words between them? I can't use anything like string split, strictly a loop and pretty simple java. Thanks!
String str = "Paul, John, Ringo";
List<String> words = new ArrayList<String>();
int cIndex = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ',') {
String temp = str.substring(cIndex, i).trim();
cIndex = i + 1;
words.add(temp);
}
}
String temp = str.substring(str.lastIndexOf(',')+1,str.length()).trim();
words.add(temp);
List<String> list = new List<String>();
String text = "your, text, here";
int indexTraversed = 0;
while(true){
int i = text.indexOf(",", indexTraversed);
if(i<0) break;
list.add(text.substring(indexTraversed, i));
indexTraversed += i + 1;
}
String[] array = list.toArray();
and if you can't use List :
String[] list = new String[100];
int counter = 0;
String text = "your, text, here";
int indexTraversed = 0; // declaring and assigning var
while(true){
int i = text.indexOf(",", indexTraversed);
if(i<0) break;
list.add(text.substring(indexTraversed, i));
indexTraversed += i + 1;
counter ++;
}
Then read the list array until counter.

Set Method And Get Method Of A Fixed Size Array

I'm a bit mixed up on how to apply the 'sets' and 'gets' methods for a fixed array. Here is some of my work in Netbeans:
//creating 5 fixed arrays of size 10
private String [] itemnames = new String [10];
private String [] itemcodes = new String [10];
private String [] category = new String [10];
private String [] quantity = new String [10];
private Double [] sellingprice = new Double [10];
//initialising each array to null in the class constructor
for (int i = 0; i < 10; i++){
itemnames[i] = "";
}
for (int i = 0; i < 10; i++){
itemcodes[i] = "";
}
for (int i = 0; i < 10; i++){
category[i] = "";
}
for (int i = 0; i < 10; i++){
quantity[i] = "";
}
for (int i = 0; i < 10; i++){
(Double.parseDouble(sellingprice[i])) = 0;
}
Now, i'm stuck in the set method and the get method of each array. Any help please?
Thanks :)
You make set and get methods according to what you want to do (or later be able to do) with the arrays.
If you want to be able to retrieve an array into another class, you could make a get method like this:
public String[] getItems()
{
return itemnames;
}
If on the other hand you only want other classes to get the specific items in your arrays, one method might look like this:
public String getItemMatchingCode(String code)
{
for(int i = 0; i < ARR_LENGTH; i++)
{
if(code.equals(itemcodes[i]) return itemnames[i];
}
}
Or you might want to set and get the different values based on ideces:
public String getItemnameAt(int i)
{
return itemnames[i];
}
public void setItemnameAt(int i, String newItemname)
{
itemnames[i] = newItemname;
}
Sidenotes:
You are not "//initialising each array to null in the class constructor", they are that by default. What you are doing is filling them with empty strings, which in most cases is unnecessary.
When iterating through the arrays and filling them with values you can do them all in one loop.
for (int i = 0; i < 10; i++)
{
itemnames[i] = "";
itemcodes[i] = "";
category[i] = "";
}
Edit:
Also consider using a constant when declaring the size of the arrays, like so:
private static final int ARR_SIZE = 10;
private String[] array = new String[ARR_SIZE];

My findCombos method does not work, How to remove characters from java character array

I am making a method which will return a String[] containing valid combinations of words that differ by one letter. The method takes as String array containing a dictionary of words as the first parameter, and two other strings containing the words one and two respectively as the second and third parameters.
Here is my method:
public static String[] findCombos(String[] dict, String a, String b){
char[] wordA = a.toCharArray();
char[] wordB = b.toCharArray();
int length = wordA.length;
List<String> validCombos = new ArrayList<String>();
Arrays.sort(dict);
//wordA
for(int i = 0; i<length; i++){
char tmp = wordA[i];
wordA[i] = 0;
String tmpWordA = new String(wordA).trim();
//tmpWordA = tmpWordA + wordA.toString().trim();
if(Arrays.binarySearch(dict, tmpWordA) >= 0){
int lengthb = wordB.length;
String tmpWordB = new String(wordB).trim();
//tmpWordB = tmpWordB + wordB.toString();
for(int j = 0; j<lengthb; j++){
tmpWordB = new StringBuffer(tmpWordB).insert(j ,tmp).toString();
if(Arrays.binarySearch(dict, tmpWordB) >= 0){
validCombos.add(tmpWordA + "\\t" + tmpWordB);//combo found
}else{
wordA[i] = tmp;
}
}
}else{
wordA[i] = tmp;
}
}
//wordB
int lengthb = b.length();
for(int i = 0; i<lengthb; i++){
char tmp = wordB[i];
wordB[i] = 0;
String tmpWordB = new String(wordB).trim();
//tmpWordB = tmpWordB + wordB.toString().trim();
if(Arrays.binarySearch(dict, tmpWordB) >= 0){
int lengtha = a.length();
String tmpWordA = new String(wordA).trim();
//tmpWordA = tmpWordA + wordA.toString();
for(int j = 0; j< lengtha; j++){
tmpWordA = new StringBuffer(tmpWordA).insert(j, tmp).toString();
if(Arrays.binarySearch(dict, tmpWordA) >= 0){
validCombos.add(tmpWordA + "\\t" + tmpWordB);//combo found
}else{
wordB[i] = tmp;
}
}
}else{
wordB[i] = tmp;
}
}
String[] res = validCombos.toArray(new String[0]);
return res;
}
The array has been sorted and I am certain that the element in question is in the array, however the search keeps returning a negative number and automatically branching to the else clause. Any ideas? Here is a link to the dictionary:
Dictionary - PasteBin
You are not removing the character at index i, you are replacing the character at index i with 0, that false assumption breaks your algorithm.
Delete a character by index from a character array with StringBuilder
String mystring = "inflation != stealing";
char[] my_char_array = mystring.toCharArray();
StringBuilder sb = new StringBuilder();
sb.append(mystring);
sb.deleteCharAt(10);
my_char_array = sb.toString().toCharArray();
System.out.println(my_char_array); //prints "inflation = stealing"
The above code removes the exclamation mark from the character array.
Roll your own java function to remove a character from a character array:
String msg = "johnny can't program, he can only be told what to type";
char[] mychararray = msg.toCharArray();
mychararray = remove_one_character_from_a_character_array_in_java(mychararray, 21);
System.out.println(mychararray);
public char[] remove_one_character_from_a_character_array_in_java(
char[] original,
int location_to_remove)
{
char[] result = new char[original.length-1];
int last_insert = 0;
for (int i = 0; i < original.length; i++){
if (i == location_to_remove)
i++;
result[last_insert++] = original[i];
}
return result;
}
//The above method prints the message with the index removed.
Source:
https://stackoverflow.com/a/11425139/445131

How to Split an Array

I'm trying to figure out how to split an array into smaller sections. I have an String array with a bunch of characters. I would like to make a new array that stores the first five of those characters in it's first index, the next five in the next index, etc..
Something like this?
String separator = new String("|");
String [] splits = string.split(separator);
Assuming you have something like this:
String[] myArray = {"12345123", "45123", "45"};
You can split it into an array of five characters like this:
String wholeString="";
for(String s : myArray)
wholeString += s;
int arrayLength = wholeString.length()/5;
if(wholeString.length()%5==0)
arrayLength--;
String[] arrayOfFive = new String[arrayLength];
int counter=0;
String buffer = "";
for(int i=0;i<s.length();i++){
buffer += s.charAt(i);
if(buffer.length()==5){
arrayOfFive[counter] = buffer;
buffer = "";
}
Now, if you don't want to get the whole array string into memory and hold it there, you can do this one character at a time:
String buffer = "";
List<String> stringList = new ArrayList<String>();
for(String s : myArray){
for(int i=0;j<s.length();i++){
buffer += s.charAt(i);
if(buffer.length()==5){
stringList.add(buffer);
buffer = new String();
}
}
}
String[] arrayOfFive = new String[stringList.length()];
stringList.toArray(arrayOfFive);
If you simply have an array of 1-character strings, then you can do it like this:
int arrayLength = myArray.length/5;
if(myArray.length%5==0)
arrayLength--;
String[] arrayOfFive = new String[arrayLength];
for(int i=0;i<myArray.length;i++){
if(i%5==0)
arrayOfFive[i/5] = "";
arrayOfFive[i/5] += myArray[i];
}
If you have a string array containing a single string of length 500, then you can get the string like this:
String myString = myArray[0];
After which you can loop through the characters in the string, breaking it up:
for(int i=0;i<myString.length();i++){
if(i%5==0)
arrayOfFive[i/5] = "";
arrayOfFive[i/5] += myString.charAt(i);
}
List<String> list=new ArrayList<String>();
int chunkSize=5;
for (int i=0; i<strings.size; i++) {
int lastChunk = strings[i].length() % chunkSize;
int chunks=strings[i].length() / chunkSize;
for (int j=0; j<chunks; j++) {
list.add(strings[i].substring(j*chunkSize,j*chunkSize+chunkSize);
}
if (lastChunk > 0) {
list.add(strings[i].substring(chunks*chunkSize, chunks*chunkSize+lastChunk);
}
}
char c[]=str.toCharArray();
int array_length=0;
int start=1;
if(str.length()%5==0)
{
array_length=str.length()/5;
}
else
array_length=str.length()/5 +1;
String s[]=new String[array_length];
for(int i=0;i<array_length;i++)
{
String temp="";
for(int j=start;j<=str.length();j++)
{
if(j%5==0)
{
temp=temp+c[j-1];
start=j+1;
break;
}
else
{
temp=temp+c[j-1];
}
}
s[i]=temp;
}
for(int i=0;i<array_length;i++)
{
System.out.println(s[i]);
}

Categories

Resources