How to convert String containing Array into an Array - java

This might have been asked before, but I spent some time looking, so here's what I have.
I have a string containing an array:
'["thing1","thing2"]'
I would like to convert it into an actual array:
["thing1","thing2"]
How would I do this?

You could create a loop that runs through the whole string, checking for indexes of quotes, then deleting them, along with the word. I'll provide an example:
ArrayList<String> list = new ArrayList<String>();
while(theString.indexOf("\"") != -1){
theString = theString.substring(theString.indexOf("\"")+1, theString.length());
list.add(theString.substring(0, theString.indexOf("\"")));
theString = theString.substring(theString.indexOf("\"")+1, theString.length());
}
I would be worried about an out of bounds error from looking past the last quote in the String, but since you're using a String version of an array, there should always be that "]" at the end. But this creates only an ArrayList. If you want to convert the ArrayList to a normal array, you could do this afterwards:
String[] array = new String[list.size()];
for(int c = 0; c < list.size(); c++){
array[c] = list.get(c);
}

You can do it using replace and split methods of String class, e.g.:
String s = "[\"thing1\",\"thing2\"]";
String[] split = s.replace("[", "").replace("]", "").split(",");
System.out.println(Arrays.toString(split));

Related

How to use String replace methods without replacing with empty Strings?

I am loading a String from a csv file and trying to make an int array with it. The problem is I keep running into a NumberFormatException which is thrown when the program finds a "" in the String array.
I don't need those empty Strings, I just want ints.
Is there a way to avoid replacing characters with empty Strings?
aLine = aLine.replaceAll(" ", "").replaceFirst(",", "");
aLine = aLine.replace(name, "").replaceAll("\"", "");
final String[] strScores = aLine.split(",");
final int[] scores = Arrays.stream(strScores)
.mapToInt(Integer::parseInt).toArray();
You could filter the stream for not empty and not null before you parse. Like,
final int[] scores = Arrays.stream(strScores)
.filter(x -> x != null && !x.isEmpty())
.mapToInt(Integer::parseInt)
.toArray();
You should use an array list because you can easily add and remove
array_list<String> list = new ArrayList<String>(); // create array list
for (int i =0; i < array_string.length;i++){
if (!string_array[i].equals("")){ // filter out empty
array_list.add(string_array[i]);
}
}
String new_string_array_without_empty = array_list.toArray(new String[0]); // convert to string array again

Splitting string at specified point [duplicate]

This question already has answers here:
How to separate specific elements in string java
(3 answers)
Closed 9 years ago.
so the method takes two parameters, first is the String you will be splitting, second is the delimiter(where to split at).
So if I pass in "abc|def" as the first parameter and "|" as the second I should get a List that returns "abc, def" the problem I'm having is that my if statement requires the delimiter is in the current string to be accessed. I can't think of a better condition, any help?
public List<String> splitIt(String string, String delimiter){
//create and init arraylist.
List<String> list = new ArrayList<String>();
//create and init newString.
String newString="";
//add string to arraylist 'list'.
list.add(string);
//loops through string.
for(int i=0;i<string.length();i++){
newString += string.charAt(i);
if(newString.contains(delimiter)){
//list.remove(string);
list.add(newString.replace(delimiter, ""));
newString="";
}
}
return list;
}
Badshaah and cmvaxter code for split using builtin function split(regex) won't work. as you pass "|" as a delimiter "sam|ple" it wont be splitted as [sam,ple] because ( | , + , * , ...) are all used in regex for other purposes.
and u can check character by character, if the delimiter is a character
loop(each char)
if(not delim)
append to list[i]
else
increment i, discard char
learning purpose it might be needed in c or c++ (even they 've strtok to split strings) to improve effeciency or to modify something differently. [may split differently not using regex]
Its best to use existing system libraries and functions.
if u want to use your function do something like
write these functions yourself
findpos(delim) // gives position of delimiter found in string
substring(pos,len) //len:size of delimiter
getlist(String str,String delim)
//for each delim found use substring and append to list
use some pattern matching algorithms like KMP or something u know.
Change your whole method to.
public List<String> splitIt(String string, String delimiter){
String[] out = string.split(delimiter);
return Arrays.asList(out);
}
Since you are iterating through the string, your if should be based on the character you are inspecting, instead of invoking contains each time:
public List<String> splitIt(String string, String delimiter){
//create and init arraylist.
List<String> list = new ArrayList<String>();
//create and init newString.
String newString="";
//add string to arraylist 'list'.
list.add(string);
//loops through string.
int lastDelimiter = 0;
for (int i=0; i<string.length(); i++) {
if (delimiter.equals("" + string.charAt(i))) {
list.add(string.substring(lastDelimiter, i));
lastDelimiter = i + 1;
}
}
if (lastDelimiter != string.length())
list.add(string.substring(lastDelimiter, string.length()));
return list;
}
For the sake of learning, I think your original attempt lends itself to a recursive solution. The general idea in this case would be:
If there are no delimiters in the string and it is not empty, return the string as the only element in a new list
Otherwise
find the first occurrence of the delimiter
extract the string from the beginning up to the delimiter, call it 'found'
remove the delimiter
recursively call this method, passing it the remainder of the string and the delimiter
append 'found' to the list returned from #4, and return that list
The String class already supports a split method that I believe does exactly what you are looking to do.
String[] s = "abc|def".split("\\|");
List<String> list = Arrays.asList(s);
If you want to do it yourself, the code might look something like this:
char delim = "|".charAt(0);
String s = "abc|def|ghi";
char[] chars = s.toCharArray();
StringBuilder sb = new StringBuilder();
List<String> list = new ArrayList<String>();
for(char c: chars){
if (c == delim){
list.add(sb.toString());
sb = new StringBuilder();
}
else{
sb.append(c);
}
}
if (sb.length() > 0) list.add(sb.toString());
System.out.println(list);

Split an array every time a letter appears to form a longer array in Java

I have split a string into an array every time a letter appeared, however I now want to split each string in the array into more arrays went another letter appears, adding an array below each split with the letter removed.
Here is my code:
private String input = "118u121u23n24"
private int y = 0;
private String[] split_main = new String[100];
private void split_u(){
String[] split = input.split("u");
for(int x=0; split.length>x; x++){
split_main[y] = split[x];
if(split.length>x+1)
split_main[y+1] = "+";
y +=2;
}
This splits my string into an array like this - creates a new array every time "u" appears and adds a plus
118
+
121
+
23n24
I now want to go through each of these arrays and look for the letter n and put it on a separate line so this will be the new array. However every time I have tried this I have got errors because I don't seem to be able to use the Split method again on the array. If using split is not possible then is there another way to do it?
118
+
121
+
23
n
24
Thanks in advance for any help.
Try this
String[] split = input.split("u|n");
u|n means that split string with by u or n, simply split string by two separator
while you want to add different separator in two levels you should write code like this.
String input = "118u121u23n24";
String[] s2;
ArrayList<String> main = new ArrayList<String>();
String[] split = input.split("u");
for(int x=0; split.length>x; x++){
s2 = split[x].split("n");
for(int k=0; k<s2.length; k++){
main.add(s2[k]);
if(s2.length>k+1)
main.add("n");
}
if(split.length>x+1)
main.add("+");
}
// print main array to test
for(int i=0;i<main.size();i++)
System.out.println(main.get(i));
I'd suggest that you simply split on all the letters at once, using a regex:
String[] split = input.split("(+|n)");
If you require the intermediate steps, then the only way to do it is to iterate through the first split, building an array of results of splitting on the second letter. If you want to do this for multiple split patterns (not just "+" and "n"), you will need a general purpose procedure. Here's sample code:
/**
* Replaces one element of a list of strings with the results of
* splitting that element with a given pattern. A copy of the pattern
* is inserted between the elements of the split.
* #param list The list of elements to be modified
* #param pattern The pattern on which to split
* #param pos The position of the element to split
* #return The number of additional elements inserted. This is the amount by
* which the list grew. If the element was not split, zero is returned.
*/
int splitElements(List<String> list, String pattern, int pos) {
String[] split = list.get(pos).split(pattern);
if (split.length > 1) {
list.set(pos++, split[0]);
for (int i = 1; i < split.length; ++i) {
list.add(pos++, pattern);
list.add(pos++, split[i]);
}
} // else nothing to do
return (split.length << 1) - 1;
}
Then you would call this with each character with which you want to split:
private String input = "118u121u23n24";
private ArrayList<String> split_main = new ArrayList<String>();
split_main.add(input);
splitElements(split_main, "+", 0);
for (int i = 0; i < len; ++i) {
i += splitElements(split_main, "n", i);
}
It's possible. Use List instead of array to make inserting new items easy.
If you want arrays only, do it in two passes: first, iterate over input and count how many more cells you need because of n, then create new array of proper size and copy input contents to it, splitting along the way.

String Manipulation in java

I have one array of strings. I want to get each of string, divide it in to 3 parts (number-string-number), and put each part in another array. At last I want to have 3 arrays which two of them store numbers and one of them stores strings. The number of spaces between numbers and strings are not fixed.
the format of the strings in the first array is:
-2.2052 dalam -2.7300
-3.0511 dan akan -0.1116
It will be great if you help me with a sample code.
Here's the algorithm you could implement :
Create your 3 output arrays. They should all have the same length as the original string array
iterate through your original array.
for each string, find the index of the first space character and the index of the last space character. (look into the javadoc of the String class for methods doing that)
extract the substring before the first space, the substring between the first and last space, and the substring after the last space. The javadoc should help you.
Convert the first and third substring into an int (see the javadoc for Double for how to do it)
store the doubles and the string into the ouput arrays.
You can use indexOf and lastIndexOf to achieve this. Try following:
String arrayWithStringAndNumber[] = new String[2];
arrayWithStringAndNumber[0] = "-2.2052 dalam -2.7300";
arrayWithStringAndNumber[1] = "-3.0511 dan akan -0.1116";
String numArray1[] = new String[2];
String numArray2[] = new String[2];
String strArray[] = new String[2];
String temp;
for (int i = 0; i < arrayWithStringAndNumber.length; i++) {
temp = arrayWithStringAndNumber[i];
numArray1[i]=temp.substring(0,temp.indexOf(" "));
numArray2[i]=temp.substring(temp.lastIndexOf(" ")+1);
strArray[i]=temp.substring(temp.indexOf(" ")+1,temp.lastIndexOf(" "));
}
Make sure all arrays are of same length.
For num arrays use type whatever you want. I think you may need double and then you can easily parse the value to fit in it.
Hope this helps.
You can use indexOf(int ch) and lastIndexOf(int ch) of String object to find the first and last whitespace character and divide the string using these two indexes. You can also trim the middle string part if needed.
So:
String[] input; // given
Double[] firstNumbers = new Double[input.length];
String[] middleParts = new String[input.length];
Double[] secondNumbers = new Double[input.length];
for(int i = 0; i < input.length; i++) {
String line = input[i];
int firstWhitespace = line.indexOf(" ");
int lastWhitespace = line.lastIndexOf(" ");
String firstNumber = line.substring(0, firstWhitespace);
String middlePart = line.substring(firstWhitespace, lastWhitespace+1);
String secondNumber = line.substring(lastWhitespace+1, line.length());
// parse numbers to double, add to an array
firstNumbers[i] = Double.parseDouble(firstNumber);
middleParts[i] = middlePart;
secondNumbers[i] = Double.parseDouble(secondNumber);
}
Usually every programming language has functions for operating on strings data. Common set of functions is
length (or len) - to get length of string
find (or indexOf or somthing like this) - to find position of character of substring
substring (or substr) - to get substring of N characters from postion P
often
left/right - to get substring of N characters from left or right string's side
Trim/leftTrim/rightTrim - to trim from left and/or right string's side all space-characters or given as function parameter character.
Always as you need to operate on strings data, try to read documentation or google. You always will find information at Internet. Good luck!

Parsing comma delimited text in Java

If I have an ArrayList that has lines of data that could look like:
bob, jones, 123-333-1111
james, lee, 234-333-2222
How do I delete the extra whitespace and get the same data back? I thought you could maybe spit the string by "," and then use trim(), but I didn't know what the syntax of that would be or how to implement that, assuming that is an ok way to do it because I'd want to put each field in an array. So in this case have a [2][3] array, and then put it back in the ArrayList after removing the whitespace. But that seems like a funny way to do it, and not scaleable if my list changed, like having an email on the end. Any thoughts? Thanks.
Edit:
Dumber question, so I'm still not sure how I can process the data, because I can't do this right:
for (String s : myList) {
String st[] = s.split(",\\s*");
}
since st[] will lose scope after the foreach loop. And if I declare String st[] beforehand, I wouldn't know how big to create my array right? Thanks.
You could just scan through the entire string and build a new string, skipping any whitespace that occurs after a comma. This would be more efficient than splitting and rejoining. Something like this should work:
String str = /* your original string from the array */;
StringBuilder sb = new StringBuilder();
boolean skip = true;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (skip && Character.isWhitespace(ch))
continue;
sb.append(ch);
if (ch == ',')
skip = true;
else
skip = false;
}
String result = sb.toString();
If you use a regex for you split, you can specify, a comma followed by optional whitespace (which includes spaces and tabs just in case).
String[] fields = mystring.split(",\\s*");
Depending on whether you want to parse each line separately or not you may first want to create an array split on a line return
String[] lines = mystring.split("\\n");
Just split() on each line with the delimiter set as ',' to get an array of Strings with the extra whitespace, and then use the trim() method on the elements of the String array, perhaps as they are being used or in advance. Remember that the trim() method gives you back a new string object (a String object is immutable).
If I understood your problem, here is a solution:
ArrayList<String> tmp = new ArrayList<String>();
tmp.add("bob, jones, 123-333-1111");
tmp.add(" james, lee, 234-333-2222");
ArrayList<String> fixedStrings = new ArrayList<String>();
for (String i : tmp) {
System.out.println(i);
String[] data = i.split(",");
String result = "";
for (int j = 0; j < data.length - 1; ++j) {
result += data[j].trim() + ", ";
}
result += data[data.length - 1].trim();
fixedStrings.add(result);
}
System.out.println(fixedStrings.get(0));
System.out.println(fixedStrings.get(1));
I guess it could be fixed not to create a second ArrayLis. But it's scalable, so if you get lines in the future like: "bob, jones , bobjones#gmail.com , 123-333-1111 " it will still work.
I've had a lot of success using this library.
Could be a bit more elegant, but it works...
ArrayList<String> strings = new ArrayList<String>();
strings.add("bob, jones, 123-333-1111");
strings.add("james, lee, 234-333-2222");
for(int i = 0; i < strings.size(); i++) {
StringBuilder builder = new StringBuilder();
for(String str: strings.get(i).split(",\\s*")) {
builder.append(str).append(" ");
}
strings.set(i, builder.toString().trim());
}
System.out.println("strings = " + strings);
I would look into:
http://download.oracle.com/docs/cd/E17476_01/javase/1.4.2/docs/api/java/lang/String.html#split(java.lang.String)
or
http://download.oracle.com/docs/cd/E17476_01/javase/1.5.0/docs/api/java/util/Scanner.html
you can use Sting.split() method in java or u can use split() method from google guava library's Splitter class as shown below
static final Splitter MY_SPLITTER = Splitter.on(',')
.trimResults()
.omitEmptyStrings();

Categories

Resources