Java convert special string to array of array - java

I want to split this string
['1','BR_1142','12,345','01-02-2012', 'Test 1'],['2','BR_1142','12,345','01-02-2012', 'Test 2']
To an array of array string in java?
Can I do it with regex or should I write a recursive function to handle this purpose?

How about something like the following
String str= "['1','BR_1142','12,345','01-02-2012', 'Test 1'],['2','BR_1142','12,345','01-02-2012', 'Test 2']";
String[] arr = str.split("\\],\\[");
String[][] arrOfArr = new String[arr.length][];
for (int i = 0; i < arr.length; i++) {
arrOfArr[i] = arr[i].replace("[", "").replace("]", "").split(",");
}

I'm not able to test this because of recent crash wiped out all my programs, but I believe you can use the JSON parsers to parse the string. You might have to wrap it in [ and ] or { and } before you parse.
See
http://answers.oreilly.com/topic/257-how-to-parse-json-in-java/
http://www.json.org/java/
How to parse a JSON and turn its values into an Array?

You could use String.split and regex look-behind in combination:
String str = "['1','BR_1142','12,345','01-02-2012', 'Test 1'],['2','BR_1142','12,345','01-02-2012', 'Test 2']";
String[] outerStrings = str.split("(?<=]),");
String[][] arrayOfArray = new String[outerStrings.length][];
for (int i=0; i < outerStrings.length; i++) {
String noBrackets = outerStrings[i].substring(1, outerStrings[i].length() - 1);
arrayOfArray[i] = noBrackets.split(",");
}

String yourString = "['1','BR_1142','12,345','01-02-2012', 'Test 1'],['2','BR_1142','12.345','01-02-2012', 'Test 2']";
yourString = yourString.substring(1, yourString.lastIndexOf("]"));
String[] arr = yourString.split("\\],\\[");
String[][] arr1 = new String[arr.length][];
int i = 0;
String regex = "(?<=['],)"; // This regex will do what you want..
for(String a : arr) {
arr1[i++] = a.split(regex);
}
for (String[] arrasd: arr1) {
for (String s: arrasd) {
System.out.println(s.replace(",", ""));
}
}

Related

How to convert/sort a String based on two symbols in Java?

I have the following string:
String string = "bbb,aaa,ccc\n222,111,333\nyyy,xxx,zzz";
And I'm trying to convert it to:
String converted = "aaa,bbb,ccc\n111,222,333\nxxx,yyy,zzz";
To be somehow sorted. This is what I have tried so far:
String[] parts = string.split("\\n");
List<String[]> list = new ArrayList<>();
for(String part : parts) {
list.add(part.split(","));
}
for(int i = 0, j = i + 1, k = j + 1; i < list.size(); i++) {
String[] part = list.get(i);
System.out.println(part[i]);
}
So I managed to get first element from each "unit" separately. But how to get all and order them so I get that result?
Can this be even simpler using Java8?
Thanks in advance!
I guess one way to do it would be:
String result = Arrays.stream(string.split("\\n"))
.map(s -> {
String[] tokens = s.split(",");
Arrays.sort(tokens);
return String.join(",", tokens);
})
.collect(Collectors.joining("\\n"));
System.out.println(result); // aaa,bbb,ccc\n111,222,333\nxxx,yyy,zzz
Just notice that in case your patterns are more complicated than \n or , - it is a good idea to extract those an separate Pattern(s)
String string = "bbb,aaa,ccc\n222,111,333\nyyy,xxx,zzz";
String converted = Arrays.stream(string.split("\\n"))
.map(s -> Arrays.stream(s.split(","))
.sorted()
.collect(Collectors.joining(",")))
.collect(Collectors.joining("\\n"));
You can have it the old fashioned way without the use of Java 8 like this:
public static void main(String[] args) {
String s = "bbb,aaa,ccc\n222,111,333\nyyy,xxx,zzz";
System.out.println(sortPerLine(s));
}
public static String sortPerLine(String lineSeparatedString) {
// first thing is to split the String by the line separator
String[] lines = lineSeparatedString.split("\n");
// create a StringBuilder that builds up the sorted String
StringBuilder sb = new StringBuilder();
// then for every resulting part
for (int i = 0; i < lines.length; i++) {
// split the part by comma and store it in a List<String>
String[] l = lines[i].split(",");
// sort the array
Arrays.sort(l);
// add the sorted values to the result String
for (int j = 0; j < l.length; j++) {
// append the value to the StringBuilder
sb.append(l[j]);
// append commas after every part but the last one
if (j < l.length - 1) {
sb.append(", ");
}
}
// append the line separator for every part but the last
if (i < lines.length - 1) {
sb.append("\n");
}
}
return sb.toString();
}
But still, Java 8 should be preferred in my opinion, so stick to one of the other answers.
The Pattern class gives you a possibility to stream directly splitted Strings.
String string = "bbb,aaa,ccc\n222,111,333\nyyy,xxx,zzz";
Pattern commaPattern = Pattern.compile(",");
String sorted = Pattern.compile("\n").splitAsStream(string)
.map(elem -> commaPattern.splitAsStream(elem).sorted().collect(Collectors.joining(",")))
.collect(Collectors.joining("\n"));

How to copy the entire values of array strings into a single string along with the empty spaces?

I'm using eclipse, so I have this argument on the run configuration:
hello HELLO hello
Apparently, it's on String[] args. Is there a method that can concatenate all the array values ALONG with the empty spaces between them?
I have tried splicing the arrays into a char arrays, used the toString method(garbage value for some reason), and even StringBuilder. But it always gives values but not the spaces itself. ##
You can use the String.join method:
String[] arr = {"hello", "HELLO", "hello"};
System.out.println(String.join(" ", arr));
String#join is available in Java 8.
Using StringBuilder:
StringBuilder sb = new StringBuilder();
String sep = "";
for (String str : arr) {
sb.append(sep);
sb.append(str);
sep = " ";
}
System.out.println(sb.toString());
try this
public static void main(String[] args)
{
String concated = "";
for(String arg:args){
concated+=arg+" ";
}
System.out.println(concated);
}
Well if I understood your question correctly, you have such array:
string[] str = new string[3] { "Hello", "HELLO", "hello"};
If you want them to have spaces between each words you can do something like
string output = "";
for(int i = 0; i< str.length; i++)
{
if(i + 1 != str.length)
{
output += str[i] + " ";
}
else
{
output += str[i];
}
}

Split String To Array

I've been trying to split an string by a character and store each split value inside an array.
In C# it can be done by calling the .ToArray() method after the Split() but such method apparently doesn't exits in Java. So I've been trying to do this like this (rs is a string list with elements separated by #) :
String t[] = new String[10];
for (int i = 0; i < rs.size(); i++) {
t = null;
t = rs.get(i).split("#");
}
But the whole split line is passed to an index of the array like:
String x = "Hello#World" -> t[0] = "Hello World" (The string is split in one line, so the array will have only one index of 0)
My question is that how can store each spit element in an index of the array like :
t[0] = "Hello"
t[1] = "World"
It sounds like your trying to loop through a list, split them then add the arrays together? What your defining as the problem with the .split method is exactly what the split method does.
ArrayList<String> rs = new ArrayList<>();
rs.add("Hello#World");
rs.add("Foo#Bar#Beckom");
String [] t = new String[0];
for(int i=0;i<rs.size();i++) {
String [] newT = rs.get(i).split("#");
String [] result = new String[newT.length+t.length];
System.arraycopy(t, 0, result, 0, t.length);
System.arraycopy(newT, 0, result, t.length, newT.length);
t = result;
}
for(int i=0;i<t.length;i++) {
System.out.println(t[i]);
}
Works just find output is:
Hello
World
Foo
Bar
Beckom
public class Test {
public static void main(String[] args) {
String hw = "Hello#World";
String[] splitHW = hw.split("#");
for(String s: splitHW){
System.out.println(s);
}
}
}
This produced following output for me:
Hello
World
Try this way:
String string = "Hello#World"
String[] parts = string.split("#");
String part1 = parts[0]; // Hello
String part2 = parts[1]; // World
It is always good to test beforehand if the string contains a #(in this case), just use String#contains().
if (string.contains("#")) {
// Split it.
} else {
throw new IllegalArgumentException(message);
}
why are you using a loop when the problem is already solved in java..
try this
String x = "Hello#World";
String[] array = x.split("#", -1);
System.out.println(array[0]+" "+array[1]);

how to get the value after certain Prefix in android?

I have a string like abc-5,xyz-9,pqr-15 Now,I want to get the value only after "-" So, how can i get that value..and i want this value in String Array?
You can try
String string = "abc-5,xyz-9,pqr-15";
String[] parts = string.split(",");
String val1 = parts[0].split("-");
.....
and so on
int pos = string.indexOf('-');
String sub = string.substring(pos);
If you have multiple values in each string, you'll have to split it first (using split method). For example:
String[] array = string.split(',');
String[] values = new String[array.length];
for(int i = 0; i < array.length; i++)
values[i] = array[i].substring(arrays[i].indexOf('-'));
Now you have the values in an array.
I would use split on your string.
String str = "abc-5,xyz-9,pqr-15";
String[] arr = str.split(",");
for (String elem: arr) {
System.out.print(elem.split("-")[1] + " : "); // Will print - `5 : 9 : 15`
}
or with Regular Expression like this: -
Matcher matcher = Pattern.compile("-(\\d+)").matcher(str);
while(matcher.find()) {
System.out.println(matcher.group(1));
}
Use:
String newString= oldString.substring(oldString.indexOf('-'));

Convert String to int array in java

I have one string:
String arr = "[1,2]";
ie "[1,2]" is like a single String.
How do I convert this arr to int array in java?
String arr = "[1,2]";
String[] items = arr.replaceAll("\\[", "").replaceAll("\\]", "").replaceAll("\\s", "").split(",");
int[] results = new int[items.length];
for (int i = 0; i < items.length; i++) {
try {
results[i] = Integer.parseInt(items[i]);
} catch (NumberFormatException nfe) {
//NOTE: write something here if you need to recover from formatting errors
};
}
Using Java 8's stream library, we can make this a one-liner (albeit a long line):
String str = "[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]";
int[] arr = Arrays.stream(str.substring(1, str.length()-1).split(","))
.map(String::trim).mapToInt(Integer::parseInt).toArray();
System.out.println(Arrays.toString(arr));
substring removes the brackets, split separates the array elements, trim removes any whitespace around the number, parseInt parses each number, and we dump the result in an array. I've included trim to make this the inverse of Arrays.toString(int[]), but this will also parse strings without whitespace, as in the question. If you only needed to parse strings from Arrays.toString, you could omit trim and use split(", ") (note the space).
final String[] strings = {"1", "2"};
final int[] ints = new int[strings.length];
for (int i=0; i < strings.length; i++) {
ints[i] = Integer.parseInt(strings[i]);
}
It looks like JSON - it might be overkill, depending on the situation, but you could consider using a JSON library (e.g. http://json.org/java/) to parse it:
String arr = "[1,2]";
JSONArray jsonArray = (JSONArray) new JSONObject(new JSONTokener("{data:"+arr+"}")).get("data");
int[] outArr = new int[jsonArray.length()];
for(int i=0; i<jsonArray.length(); i++) {
outArr[i] = jsonArray.getInt(i);
}
Saul's answer can be better implemented splitting the string like this:
string = string.replaceAll("[\\p{Z}\\s]+", "");
String[] array = string.substring(1, string.length() - 1).split(",");
try this one, it might be helpful for you
String arr= "[1,2]";
int[] arr=Stream.of(str.replaceAll("[\\[\\]\\, ]", "").split("")).mapToInt(Integer::parseInt).toArray();
You can do it easily by using StringTokenizer class defined in java.util package.
void main()
{
int i=0;
int n[]=new int[2];//for integer array of numbers
String st="[1,2]";
StringTokenizer stk=new StringTokenizer(st,"[,]"); //"[,]" is the delimeter
String s[]=new String[2];//for String array of numbers
while(stk.hasMoreTokens())
{
s[i]=stk.nextToken();
n[i]=Integer.parseInt(s[i]);//Converting into Integer
i++;
}
for(i=0;i<2;i++)
System.out.println("number["+i+"]="+n[i]);
}
Output :-number[0]=1
number[1]=2
String str = "1,2,3,4,5,6,7,8,9,0";
String items[] = str.split(",");
int ent[] = new int[items.length];
for(i=0;i<items.length;i++){
try{
ent[i] = Integer.parseInt(items[i]);
System.out.println("#"+i+": "+ent[i]);//Para probar
}catch(NumberFormatException e){
//Error
}
}
If you prefer an Integer[] instead array of an int[] array:
Integer[]
String str = "[1,2]";
String plainStr = str.substring(1, str.length()-1); // clear braces []
String[] parts = plainStr.split(",");
Integer[] result = Stream.of(parts).mapToInt(Integer::parseInt).boxed().toArray(Integer[]::new);
int[]
String str = "[1,2]";
String plainStr = str.substring(1, str.length()-1); // clear braces []
String[] parts = plainStr.split(",");
int[] result = Stream.of(parts).mapToInt(Integer::parseInt).toArray()
This works for Java 8 and higher.
In tight loops or on mobile devices it's not a good idea to generate lots of garbage through short-lived String objects, especially when parsing long arrays.
The method in my answer parses data without generating garbage, but it does not deal with invalid data gracefully and cannot parse negative numbers. If your data comes from untrusted source, you should be doing some additional validation or use one of the alternatives provided in other answers.
public static void readToArray(String line, int[] resultArray) {
int index = 0;
int number = 0;
for (int i = 0, n = line.length(); i < n; i++) {
char c = line.charAt(i);
if (c == ',') {
resultArray[index] = number;
index++;
number = 0;
}
else if (Character.isDigit(c)) {
int digit = Character.getNumericValue(c);
number = number * 10 + digit;
}
}
if (index < resultArray.length) {
resultArray[index] = number;
}
}
public static int[] toArray(String line) {
int[] result = new int[countOccurrences(line, ',') + 1];
readToArray(line, result);
return result;
}
public static int countOccurrences(String haystack, char needle) {
int count = 0;
for (int i=0; i < haystack.length(); i++) {
if (haystack.charAt(i) == needle) {
count++;
}
}
return count;
}
countOccurrences implementation was shamelessly stolen from John Skeet
String arr= "[1,2]";
List<Integer> arrList= JSON.parseArray(arr,Integer.class).stream().collect(Collectors.toList());
Integer[] intArr = ArrayUtils.toObject(arrList.stream().mapToInt(Integer::intValue).toArray());

Categories