How to Split an Array - java

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]);
}

Related

Java splitting string using delimiter and store to different array

I was having some problem when trying to split string with delimiter and store to array. So basically I have a main array with input like this:
1564095_SINGLE_true, 1564096_SINGLE_true
What I am trying to do is split the string with delimiter and store to two different array. Below as how I loop thru the main array:
String arrayA = [];
String arrayB = [];
for(int i = 0; i < selectedRecord.length; i++) {
log.debug("HEY " + selectedRecord[i]);
String tempRecord = selectedRecord[i];
}
My desired output will be:
arrayA: 1564095_SINGLE, 1564096_SINGLE
arrayB: true, true
But I have no idea on how to split it. Any ideas? Thanks!
Here is one approach which splits in the input on the following regex pattern:
_(?!.*_)
This splits the input string on only the last underscore character. We can try iterating your collection of inputs, and then populating the two arrays.
List<String> inputs = Arrays.asList(new String[] {"1564095_SINGLE_true", "1564096_SINGLE_true"});
String[] arrayA = new String[2];
String[] arrayB = new String[2];
int index = 0;
for (String input : inputs) {
arrayA[index] = input.split("_(?!.*_)")[0];
arrayB[index] = input.split("_(?!.*_)")[1];
++index;
}
System.out.println("A[]: " + Arrays.toString(arrayA));
System.out.println("B[]: " + Arrays.toString(arrayB));
This prints:
A[]: [1564095_SINGLE, 1564096_SINGLE]
B[]: [true, true]
Does this help? Assuming you can apply basic checks (null, array length, etc)
String[] selectedRecord = {"1564095_SINGLE_true", "1564096_SINGLE_true"};
String[] arrayA = new String[selectedRecord.length];
String[] arrayB = new String[selectedRecord.length];
for (int i = 0; i < selectedRecord.length; i++) {
arrayA[i] = selectedRecord[i].substring(0, selectedRecord[i].lastIndexOf("_"));
arrayB[i] = selectedRecord[i].substring(selectedRecord[i].lastIndexOf("_")+1);
}
System.out.println(Arrays.asList(arrayA));
System.out.println(Arrays.asList(arrayB));
check below code
import java.util.*;
public class MyClass {
public static void main(String args[]) {
String str="1564095_SINGLE_true, 1564096_SINGLE_true";
System.out.println(str);
String arr[]=str.split(",");
ArrayList<String> arr1=new ArrayList();
ArrayList<String> arr2=new ArrayList();
for(int i=0;i<arr.length;i++)
{
String temp[]= arr[i].split("_");
for(int j=0;j<temp.length;j++)
{
if(j==2)
{
arr2.add(temp[j]);
}
else
{
arr1.add(temp[j]);
}
}
}
System.out.println(arr1);
System.out.println(arr2);
}
}
String selectedRecord[] = { "1564095_SINGLE_true", "1564096_SINGLE_true" };
String[] arrayA = new String[selectedRecord.length];
String[] arrayB = new String[selectedRecord.length];
for(int i = 0; i < selectedRecord.length; i++) {
String tempRecord = selectedRecord[i];
int size = tempRecord.split("_").length;
arrayB[i]= tempRecord.split("_")[size-1];
arrayA[i]= tempRecord.replace("_"+arrayB[i], "");
}
System.out.println("ArrayA: "+ Arrays.asList(arrayA));
System.out.println("ArrayB: "+ Arrays.asList(arrayB));
Output:
ArrayA: [1564095_SINGLE, 1564096_SINGLE]
ArrayB: [true, true]
Hi you can do something like this. Get the last index of the delimiter and substring the string.
String arrayA = [];
String arrayB = [];
for(int i = 0; i < selectedRecord.length; i++) {
int end = selectedRecord.lastIndexOf("_");
arrayA[i] = selectedRecord.substring(0, end);
arrayB[i] = selectedRecord.substring(end+1);
}
Of course here should be some datatype conversions. If you want to store "true"/"false" inside of the boolean array.

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,

How do I split a string into even parts then populate an array with those new strings?

I am working on a program and I will be asking the user to input a string full of characters with no spaces. I will then be splitting this string up into parts of three characters each, and I would like to populate an array with these new strings of three characters. So basically what I am asking is how would I create a method that takes an input string, splits it up into separate parts of three, then populates an array with it.
while (i <= DNAstrand.length()-3) {
DNAstrand.substring(i,i+=3));
}
This code will split the string up into parts of three, but how do I assign those values to an array in a method?
Any help is appreciated thanks!
Loop through and add all the inputs to an array.
String in = "Some input";
//in.length()/3 is automatically floored
String[] out = new String[in.length()/3];
int i=0;
while (i<in.length()-3) {
out[i/3] = in.substring(i, i+=3);
}
This will ignore the end of the String if it's length isn't a multiple of 3. The end can be found with:
String remainder = in.substring(i, in.length());
Finally, if you want the remainder to be part of the array:
String in = "Some input";
//This is the same as ceiling in.length()/3
String[] out = new String[(in.length()-1)/3 + 1];
int i=0;
while (i<in.length()-3) {
out[i/3] = in.substring(i, i+=3);
}
out[out.length-1] = in.substring(i, in.length());
Try this:
private static ArrayList<String> splitText(String text)
{
ArrayList<String> arr = new ArrayList<String>();
String temp = "";
int count = 0;
for(int i = 0; i < text.length(); i++)
{
if(count < 3)
{
temp += String.valueOf(text.charAt(i));
count++;
if(count == 3)
{
arr.add(temp);
temp = "";
count = 0;
}
}
}
if(temp.length() < 3)arr.add(temp);//in case the string is not evenly divided by 3
return arr;
}
You can call this method like this:
ArrayList<Strings> arrList = splitText(and the string you want to split);

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.

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

Categories

Resources