Convert a String to String Array in Android - java

I have 3 String like this:
["state","in",["assigned", "partially_available"]]
["state","in",["confirmed", "waiting"]]
["state","in",["confirmed", "waiting", "assigned"]]
Now I want to convert each string to 2 arrays with first 2 elements is a array and others elements is a array(Ex: ["state", "in"] ["asigned", "partially_available"]). Any way to do that? Thank you very much!

String s = "[state,in,[assigned, partially_available]]";
s = s.substring(1,s.length()-1); // removes first and last square bracket
String[] sArr = s.split(",(?! )"); // split only the comma which is not followed by a space character
String[] newArr1 = {sArr[0],sArr[1]}; // first array containing ["state","in"]
String temp = sArr[2].substring(1,sArr[2].length()-1); // remove the square brackets from the inner array
String[] newArr2 = {temp.split(",")[0],temp.split(",")[1]}; // second array containing ["asigned", "partially_available"]

Try this.
public class TestArray{
public static void main(String[] args) {
String string = "[state,in,[assigned, partially_available]]";
String[] tempstr = string.split("\\["); //remove "["
String arrayFirstElement = tempstr[1].substring(0,tempstr[1].length()-1);
String arraySecondElement = tempstr[2].substring(0, tempstr[2].length()-2);
System.out.println("arrayFirstElement : " + arrayFirstElement);
System.out.println("arraySecondElement : " + arraySecondElement);
String[] strArray = new String[2];
strArray[0] = arrayFirstElement;
strArray[1] = arraySecondElement;
System.out.println("strArray[0] : " + strArray[0] + " AND strArray[1] : " + strArray[1]);
}
}

Related

Why can I not store a value in my 2d String array from my normal String Array

I need to create a 2d with 2 rows, one to hold unique string and the other the number of times the string appeared in the string array im getting the words form, cannot put values into my 2d because its null.
public lexNode() throws IOException {
path = "src\\words.txt";
String content = Files.readString(Paths.get(path), StandardCharsets.UTF_8);
allWords = content.split("[^a-zA-Z]+");
String[][] allWords2 = new String[2][];
String wordsUsed;
for(int i = 0, j = 0; i < allWords.length; i++){
wordsUsed = allWords[i];
allWords2[1][j] = "1";
if (!(wordsUsed.contains(allWords[i]))){
allWords2[0][j] = allWords[i];
allWords2[1][j] = "1";
j++;
}else if(wordsUsed.contains(allWords[i])){
int idx = Arrays.asList(allWords2[0]).indexOf(allWords[i]);
allWords2[1][idx] = Integer.toString(Integer.parseInt(allWords2[1][idx]) + 1);
}
}
I tried putting in values before the for loop, I cant use hashmaps because the getKey wont find the string I'm looking for, its always false as i altered the hashmap to count number of occurrences a word appeared. Thats a question for another thread.
See below how 2D arrays are defined & declared (or memory allocated) before values can be assigned.
public class Main {
public static void main(String[] args) {
versionOne();
versionTwo();
}
public static void versionOne() {
String[][] allWords2 = new String[2][]; //2d is defined
allWords2[0] = new String[2]; // inner array allocated
allWords2[0][0] = "Hello";
allWords2[0][1] = "World";
System.out.println("Ver1>> " + allWords2[0][0] + " " + allWords2[0][1]);
}
public static void versionTwo() {
String[][] allWords2 = new String[2][2]; //2d is defined & allocated
allWords2[0][0] = "Hello";
allWords2[0][1] = "World";
System.out.println("ver2>> " + allWords2[0][0] + " " + allWords2[0][1]);
}
}

How to split a String by a comma, but from the second comma

I have a string as:
"model=iPhone12,3,os_version=13.6.1,os_update_exist=1,status=1"
How can I convert this into:
model=iPhone12,3
os_version=13.6.1
os_update_exist=1
status=1
Split the string from the first comma, then re-join the first two elements of the resulting string array.
I doubt there's a "clean" way to do this but this would work for your case:
String str = "model=iPhone12,3,os_version=13.6.1,os_update_exist=1,status=1";
String[] sp = str.split(",");
sp[0] += "," + sp[1];
sp[1] = sp[2];
sp[2] = sp[3];
sp[3] = sp[4];
sp[4] = "";
You can try this:
public String[] splitString(String source) {
// Split the source string based on a comma followed by letters and numbers.
// Basically "model=iPhone12,3,os_version=13.6.1,os_update_exist=1,status=1" will be split
// like this:
// model=iPhone12,3
// ,os_version=13.6.1
// ,os_update_exist=1
// ,status=1"
String[] result = source.split("(?=,[a-z]+\\d*)");
for (int i = 0; i < result.length; i++) {
// Removes the comma at the beginning of the string if present
if (result[i].matches(",.*")) {
result[i] = result[i].substring(1);
}
}
return result;
}
if you are parsing always the same kind of String a regex like this will be do the job
String str = "model=iPhone12,3,os_version=13.6.1,os_update_exist=1,status=1";
Matcher m = Pattern.compile("model=(.*),os_version=(.*),os_update_exist=(.*),status=(.*)").matcher(str);
if (m.find()) {
model = m.group(1)); // iPhone12,3
os = m.group(2)); // 13.6.1
update = m.group(3)); // 1
status = m.group(4)); // 1
}
If you really wants to use a split you can still use that kind of trick
String[] split = str.replaceAll(".*?=(.*?)(,[a-z]|$)", "$1#")
.split("#");
split[0] // iPhone12,3
split[1] // 13.6.1
split[2] // 1
split[3] // 1

Split and pair substrings by condition

I have a string like this: "aa-bb,ccdd,eeff,gg-gg,cc-gg". I need to split the string by '-' signs and create two strings from it, but if the comma-delimited part of the original string doesn't contain '-', some placeholder character needs to be used instead of substring. In case of above example output should be:
String 1:
"{aa,ccdd,eeff,gg,cc}"
String 2:
"{bb,0,0,gg,gg}"
I can't use the lastIndexOf() method because input is in one string. I am not sure how to much the parts.
if(rawIndication.contains("-")){
String[] parts = rawIndication.split("-");
String part1 = parts[0];
String part2 = parts[1];
}
Here is a Java 8 solution, using streams. The logic is to first split the input string on comma, generating an array of terms. Then, for each term, we split again on dash, retaining the first entry. In the case of a term having no dashes, the entire string would just be retained. Finally, we concatenate back into an output string.
String input = "aa-bb,ccdd,eeff,gg-gg,cc-gg";
int pos = 1;
String output = String.join(",", Arrays.stream(parts)
.map(e -> e.split("-").length >= (pos+1) ? e.split("-")[pos] : "0")
.toArray(String[]::new));
System.out.println(output);
This outputs:
bb,0,0,gg,gg
List<String> list1 = new ArrayList<>();
List<String> list2 = new ArrayList<>();
// First split the source String by comma to separate main parts
String[] mainParts = sourceStr.split(",");
for (String mainPart: mainParts) {
// Check if each part contains '-' character
if (mainPart.contains("-")) {
// If contains '-', split and add the 2 parts to 2 arrays
String[] subParts = mainPart.split("-");
list1.add(subParts[0]);
list2.add(subParts[1]);
} else {
// If does not contain '-', add complete part to 1st array and add placeholder to 2nd array
list1.add(mainPart);
list2.add("0");
}
}
// Build the final Strings by joining String parts by commas and enclosing between parentheses
String str1 = "{" + String.join(",", list1) + "}";
String str2 = "{" + String.join(",", list2) + "}";
System.out.println(str1);
System.out.println(str2);
With the way you structured the problem, you should actually be splitting by commas first. Then, you should iterate through the result of the call to split and split each string in the outputted array by hyphen if there exists one. If there isn't a hyphen, then you can add a 0 to string 2 and the string itself to string 1. If there is a hyphen, then add the left side to string 1 and the right side to string 2. Here's one way you can do this,
if(rawIndication.contains(",")){
String s1 = "{";
String s2 = "{";
String[] parts = rawIndication.split(",");
for(int i = 0; i < parts.length; i++) {
if(parts[i].contains("-") {
String[] moreParts = parts[i].split(",");
s1 = s1 + moreParts[0] + ",";
s2 = s2 + moreParts[1] + ",";
}
else{
s1 = s1 + parts[i] + ",";
s2 = "0,";
}
}
s1 = s1.substring(0, s1.length() - 1); //remove last extra comma
s2 = s2.substring(0, s2.length() - 1); //remove last extra comma
s1 = s1 + "}";
s2 = s2 + "}";
}
I think this solves your problem.
private static void splitStrings() {
List<String> list = Arrays.asList("aa-bb", "ccdd", "eeff", "gg-gg", "cc-gg");
List firstPartList = new ArrayList<>();
List secondPartList = new ArrayList<>();
for (String undividedString : list){
if(undividedString.contains("-")){
String[] dividedParts = undividedString.split("-");
String firstPart = dividedParts[0];
String secondPart = dividedParts[1];
firstPartList.add(firstPart);
secondPartList.add(secondPart);
} else{
firstPartList.add(undividedString);
secondPartList.add("0");
}
}
System.out.println(firstPartList);
System.out.println(secondPartList);
}
Output is -
[aa, ccdd, eeff, gg, cc]
[bb, 0, 0, gg, gg]

Random sentence generator returning numbers and not sentence

I am suppose to create a random sentence generator. I have done everything but when I run a test, instead of returning a sentence it returns a number.
Example:
If it should return "A beautiful car explodes.", returns 0100. instead.
I am pretty sure I am missing something but at this point I cannot figure it out. I believe my test is written wrong, but I am not sure. Any help would be appreciated. Thank you!
public class set2{
public static void main(String[] args) {
String[] article = new String[4];
String[] adj = new String[2];
String[] noun = new String[2];
String[] verb = new String[3];
article[0] = "A";
article[1] = "The";
article[2] = "One";
article[3] = "That";
adj[0] = "hideous";
adj[1] = "beautiful";
noun[0] = "car";
noun[1] = "woman";
verb[0] = "explodes";
verb[1] = "is dying";
verb[2] = "is moving";
// Test for randomSentence
System.out.println(randomSentence(article, adj, noun, verb));
public static String randomSentence(String[] article, String[] adj, String[] noun, String[] verb) {
Random rand = new Random();
int articledx = rand.nextInt(article.length);
int adjdx = rand.nextInt(adj.length);
int noundx = rand.nextInt(noun.length);
int verbdx = rand.nextInt(verb.length);
String sentence = articledx + "" + adjdx + "" + noundx + "" + verbdx + ".";
return sentence;
You're returning numbers, not the element of the array at the number. To return the element of an array at a certain index, you'll use the syntax
arrayElementAtIndex = arrayName[arrayIndex];
Also, you need to include spaces in your strings to make spaces.
Change your second to last line to
String sentence = article[articledx] + " " + adj[adjdx] + " " + noun[noundx] + " " + verb[verbdx] + ".";
As long as your indexes are correct, it'll work.
The problem is that you are building the result based on the random int you generate and not the elements pointed in the correspondingly arrays...
modify the String sentence
like:
String sentence = article[articledx[ + "" + adj[adjdx]+ "" + noun[noundx] + "" + verb[verbdx] + ".";
public static String randomSentence(String[] article, String[] adj, String[] noun, String[] verb) {
Random rand = new Random();
int articledx = rand.nextInt(article.length);
int adjdx = rand.nextInt(adj.length);
int noundx = rand.nextInt(noun.length);
int verbdx = rand.nextInt(verb.length);
return article[articledx[ + "" + adj[adjdx]+ "" + noun[noundx] + "" + verb[verbdx] + ".";

Check if a substring contains a certain value

Is it possible to check if a substring contains a certain value and do something? I have this piece of code i'm wondering if I could check if desc: contains the value \n I have the config made with the following information
test: desc:\ndog\ntest
test2: desc:\ndog3
So how would I be able to retrieve the \n and loop through all the \n in that specific string list and do a action.
for (String s : plugin.file.getFile().getStringList(plugin.file.path))
{
public void substring(){
String labels = "item: desc:";
String[] parts = labels.split(" ");
String part1 = parts[0];
String part2 = parts[1];
System.out.println("Desc Value: " + s.substring(part2.length()).split(" ")[1])
}
}
I don't understand your question in full but I think that you want something like this:
String test = "desc:\ndog\ntest";
String test1 = "desc:\ndog3";
String[] parts = test.split(":");
String name = parts[0];
String[] values = parts[1].trim().split("\n");
System.out.println("Name: " + name);
for (int i = 0; i<values.length; i++)
{
System.out.println(values[i]);
}
You just split the values of [1] index in that parts table.

Categories

Resources