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.
Related
I have a string array for example:
new String[] = {"powerhouse", "p, pow, power, house, pose, poser"};
My goal is to split the first entry in the array in this case powerhouse into any two words and check them against the second entry, which serves as a dictionary of words.
Here's my implementation so far:
public static String[] convertWordsToArray(String input){
String[] wordArr = null;
wordArr = input.split(",");
return wordArr;
}
public static String splitEm(String[] strArr) {
String fw = strArr[0];
String sw = strArr[1];
String[] arrOne = convertWordsToArray(fw);
System.out.println(arrOne.length);
String[] dict = convertWordsToArray(sw);
System.out.println(dict.length);
for(int i = 0; i < dict.length - 1; i++) {
String mWord = fw.split(i, i + 1);
System.out.println(mWord);
}
// Edit Starts Here, tried to substring it but nothing prints in log
for(int i = 0; i < arrOne.length; i++) {
String mWord = fw.substring(0, i);
System.out.println(mWord);
}
return ""; // empty for now
}
I am stuck at the part where the first word has to be split. Should I use two loops, one for the first word and the other for the dictionary? I know that somehow the dictionary has to be converted to a list or array list to avail the .contains() method. How do I go about this? Thanks.
If anyone want the solution for PHP language, then you can use below code:
function ArrayChallenge($strArr) {
$dictWords = explode( ',', $strArr[1] );
$strLength = strlen($strArr[0]);
$output = 'not possible';
for( $i = 1; $i < $strLength; $i++ ){
$firstStr = substr($strArr[0], 0, $i);
$lastStr = substr($strArr[0], $i, $strLength);
if ( in_array( $firstStr, $dictWords ) && in_array( $lastStr, $dictWords ) ) {
$output = $firstStr . ',' . $lastStr;
break;
}
}
return $output;
}
Do you need something like this?
String s = "powerhouse";
List<String> list = new ArrayList<String>();
for(int i = 0; i < s.length(); i++){
for(int j = i+1; j <= s.length(); j++){
list.add(s.substring(i,j));
}
}
System.out.println(list);
I assume you need something like below:
Split second string at each , or even better using regex to trim
spaces before or after ,
check if each part of the splited entry fro above point is made of
only the chars contained in the first entry of your input
example
public static void main(String args[]) {
String[] test1 = {"powerhouse", "p, pow, power, house, pose, poser"};
String[] test2 = {"powerhouse", "p, xyz, power, house, pose, poser"};
System.out.println(check(test1));
System.out.println(check(test2));
}
static boolean check(String[] input){
String firstEntry = input[0];
String[] dictionary = input[1].split("\\s*,\\s*");
for(int i = 0; i < dictionary.length; i++){
if(!dictionary[i].matches("["+firstEntry+"]+")){
return false;
}
}
return true;
}
this will print true for the first case and false for the second as "xyz" is not a valid subpart/substring according to your discription
Try this :
public class Stack {
public static void main(String[] args) {
String[] str = {"powerhouse", "p, pow, power, house, pose, poser"};
String firstPart = str[0];
String secondPart = str[1];
boolean contain = isContain(firstPart, secondPart);
System.out.println(contain);
}
private static boolean isContain(String firstPart, String secondPart) {
for (int i = 0; i < firstPart.length(); i++) {
String firstWord = firstPart.substring(0, i);
String secondWord = firstPart.substring(i, firstPart.length());
List<String> strings = Arrays.asList(secondPart.trim().split("\\s*,\\s*"));
if (strings.contains(firstWord) && strings.contains(secondWord)) return true; if you want to check both words use this
//if (strings.contains(firstWord) || strings.contains(secondWord)) return true; if you want to check any(one) word from two words use this
}
return false;
}
}
Ok so I'm working on this code to blend humanities and STEM. I know very basic java code and so I'm currently trying to stick to String methods. I know using arrays may be easier but I'm not well learned in how to use them. So so far I've made code that counts the words in the string in order to determine how many words to remove (half of them). Next I need to figure out a way to randomly remove half of the words and return a new string, possibly with spaces replacing the removed letters.
Here is my code so far:
public class wordcount
{
public static void main (String[] args)
{
System.out.println("Simple Java Word Count Program");
String str1 = "Look, you want it you devour it and then, then good as it was you realize it wasn’t what you exactly wanted what you wanted exactly was wanting";
String[] wordArray = str1.split("\\s+");
int wordCount = wordArray.length;
System.out.println(str1 + "");
System.out.println("Word count is = " + wordCount);
int wordCount2 = wordCount/2;
}
}
I copied the array to an arrayList to then iterate through the list and delete random elements. I hope this is the type of answer you are looking for.
public static void main(String[] args) {
String str1 = "Look, you want it you devour it and then, then good as it was you realize it wasn’t what you exactly wanted what you wanted exactly was wanting";
String[] wordArray = str1.split("\\s+");
ArrayList<String> wordList = new ArrayList<String>(Arrays.asList(wordArray));
int wordCount = wordList.size();
int halfWordCount = wordCount/2;
int tracker = 0; //counter for iterations in while loop
Random random = new Random();
while(tracker < halfWordCount){
int randomIndex = random.nextInt(wordList.size());
wordList.remove(randomIndex);
tracker++;
}
System.out.println(wordList.toString());
}
import java.util.Arrays;
import java.util.* ;
public class wordcount
{
public ArrayList<Integer> test(Integer[] array)
{
ArrayList<Integer> list = new ArrayList<Integer>();
for(int i=0; i<array.length; i++)
list.add(array[i]);
return list;
}
public ArrayList<String> testS(String[] array)
{
ArrayList<String> list = new ArrayList<String>();
for(int i=0; i<array.length; i++)
list.add(array[i]);
return list;
}
public static void main (String[] args)
{
System.out.println("Removing random words in a Poem Program");
String str1 = "Sample Poem by Noah Eli Gordon: Look, you want it you devour it and then, then good as it was you realize it wasn’t what you exactly wanted what you wanted exactly was wanting";
String[] wordArray = str1.split("\\s+");
int wordCount = wordArray.length;
System.out.println(str1 + "");
//System.out.println("Word count is = " + wordCount);
//System.out.println(wordArray);
//String[] ret = wordArray;
//for(String str : ret)
// System.out.print(str);
int wordCount2 = wordCount/2;
Integer[] myIntArray = new Integer[wordCount];
//for(int i = 0; i<wordCount;i++)
// myIntArray[i] = i;
//for(int str : myIntArray)
//System.out.print(str);
wordcount w = new wordcount();
String[] wordArray2 = new String[wordCount2];
for(int i = 0; i <= wordCount2; i++)
{
int rand = (int)(Math.random()*(myIntArray.length-1));
ArrayList<Integer> list = w.test(myIntArray);
list.remove(rand);
myIntArray = list.toArray(myIntArray);
ArrayList<String> listS = w.testS(wordArray);
listS.remove(rand);
wordArray2 = listS.toArray(wordArray);
}
List<String> list = new ArrayList<String>();
for(String s : wordArray2)
{
if(s != null && s.length() > 0)
{
list.add(s);
}
}
wordArray2 = list.toArray(new String[list.size()]);
//for(int str : myIntArray)
//System.out.println(str);
System.out.println();
String[] ret2 = wordArray2;
for(String str : ret2)
System.out.print(str + " ");
}
}
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);
I want to generate possible tokens using forward traversal in Java. For example if I have a string "This is my car". I need to generate tokens
"This is my car"
"This is my"
"This is"
"This"
"is my car"
"is my"
"is"
"my car"
"my"
"car"
What is the best way to do this? Any examples? Thanks.
Here is another solution with split and nested loops:
public static void main(String[] args) {
String original = "this is my car";
String[] singleWords = original.split(" "); // split the String to get the single words
ArrayList<String> results = new ArrayList<String>(); // a container for all the possible sentences
for (int startWord = 0; startWord < singleWords.length; startWord++) { // starWords start with 0 and increment just until they reach the last word
for (int lastWord = singleWords.length; lastWord > startWord; lastWord--) { // last words start at the end and decrement just until they reached the first word
String next = "";
for (int i = startWord; i != lastWord; i++) { // put all words in one String (starting with the startWord and ending with the lastWord)
next += singleWords[i] + " ";
}
results.add(next); // add the next result to your result list
}
}
// this is just to check the results. All your sentences are now stored in the ArrayList results
for (String string : results) {
System.out.println("" + string);
}
}
and this was my result when I tested the method:
this is my car
this is my
this is
this
is my car
is my
is
my car
my
car
Use Guava:
String yourOriginalString = "This is my car";
final Set<String> originalWords =
Sets.newLinkedHashSet(
Splitter.on(CharMatcher.WHITESPACE).trimResults().split(yourOriginalString));
final Set<Set<String>> variations = Sets.powerSet(originalWords);
for (Set<String> variation : variations) {
System.out.println(Joiner.on(' ').join(variation));
}
Output:
This
is
This is
my
This my
is my
This is my
car
This car
is car
This is car
my car
This my car
is my car
This is my car
Here is a possible way:
//Just a method that seperates your String into an array of words based on the spaces
//I'll leave that for you to figure out how to make
String[] array = getSeperatedWords(<yourword>);
List<StringBuffer> bufferArray = new ArrayList<StringBuffer>();
for(int i = 0; i < array.length; i++){
StringBuffer nowWord = array[i];
for(int j = i; j < array.length; j++{
nowWord.append(array[j]);
}
bufferArray.add(nowWord);
}
for(int i = 0; i < bufferArray.length; i++){
System.out.print(bufferArray.get(i));
}
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
String var = "This is my car";
permute(var);
}
public static void permute(String var) {
if(var.isEmpty())
return;
String[] arr = var.split(" ");
while(arr.length > 0) {
for(String str : arr) {
System.out.print(str + " ");
}
arr = (String[]) Arrays.copyOfRange(arr, 0, arr.length - 1);
System.out.println();
}
String[] original = var.split(" ");
permute(implodeArray((String[]) Arrays.copyOfRange(original, 1, original.length), " "));
}
public static String implodeArray(String[] inputArray, String glueString) {
String output = "";
if (inputArray.length > 0) {
StringBuilder sb = new StringBuilder();
sb.append(inputArray[0]);
for (int i=1; i<inputArray.length; i++) {
sb.append(glueString);
sb.append(inputArray[i]);
}
output = sb.toString();
}
return output;
}
}
Read this book, you will be a master on recursion: http://mitpress.mit.edu/sicp/
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]);
}