How to convert String[] to String and vice versa in Android - java

I want to convert a String Array to String so that later on while retrieving I can parse String to String[] with the help of (,) separator.
String [] ------------> String
//and later
String ---------------> String[]
Can someone guide on how to do this?
for (int i = 0; i <= count; i++) {
Log.d(TAG, "arrayData == " +arrayData[i]);
// Joining:
String joined = String.join(",", arrayData);
//This will give error "The method join(String, String[]) is undefined for the type String"
}

You can use String.join StringBuilder and String.split:
// Joining:
String joined = String.join(",", stringArr);
StringBuilder buffer = new StringBuilder();
for (String each : stringArr)
buffer.append(",").append(each);
String joined = buffer.deleteCharAt(0).toString();
// Splitting:
String[] splitted = joined.split(",");

Related

Java 6 converting utf8 to iso88591 charset and ignoring unmappable characters

I have written the following function which gets rid of characters in a string that can't be represented in iso88591:
public static String convert(String str) {
if (str.length()==0) return str;
str = str.replace("–","-");
str = str.replace("“","\"");
str = str.replace("”","\"");
return new String(str.getBytes(),iso88591charset);
}
My problem is this doesn't have the behavior I require.
When it comes across a character that has no representation it is converted to multiple bytes. I want that character to be simply omitted from the result.
I would also like to somehow not have to have all those replace commands.
I have been researching charsetEnocder. It has methods like:
CharsetEncoder encoder = iso88591charset.newEncoder();
encoder.onMalformedInput(CodingErrorAction.IGNORE);
encoder.onUnmappableCharacter(CodingErrorAction.IGNORE);
which seem to be what I want, but I have failed to even write a function that mimics what I already have using charset encoder yet alone get to set those options.
Also I am restricted to Java 6 :(
Update:
I came up with a nasty solution for this, but there must be a better way to do it:
public static String convert(String str) {
if (str.length()==0) return str;
str = str.replace("–","-");
str = str.replace("“","\"");
str = str.replace("”","\"");
String str2 = "";
for (int c=0;c<str.length();c++) {
String cur = (new Character(str.charAt(c))).toString();
if (cur.equals(new String(cur.getBytes(),iso88591charset))) str2 += cur;
}
return new String(str2.getBytes(),iso88591charset);
}
One possibile way could be
// U+2126 - omega sign
// U+2013 - en dash
// U+201c - left double quotation mark
// U+201d - right double quotation mark
String str = "\u2126\u2013\u201c\u201d";
System.out.println("original = " + str);
str = str.replace("–", "-");
str = str.replace("“", "\"");
str = str.replace("”", "\"");
System.out.println("replaced = " + str);
StringBuilder sb = new StringBuilder();
for (char c : str.toCharArray()) {
if (c <= '\u00ff') {
sb.append(c);
}
}
System.out.println("stripped = " + sb);
output
original = Ω–“”
replaced = Ω-""
stripped = -""

Convert ArrayList of Integers to String Java

I want to convert an ArrayList of Integers to a single string.
For example:
List<Integers> listInt= new ArrayList();
String str = "";
listInt.add(1);
listInt.add(2);
listInt.add(3);
// I want the output to be: str = "123";
String numberString = listInt.stream().map(String::valueOf)
.collect(Collectors.joining(""));
//You can pass a delimiter if you want to the joining() function, like a comma. ","
Try this, the simplest way:
List<Integer> listInt = Arrays.asList(1,2,3);
String str = "";
StringBuilder builder = new StringBuilder();
for(Integer item : listInt)
builder.append(item);
str = builder.toString();
System.out.println(str);

How to remove last character string in java

I want to remove comma in last data.
example:
i have code:
StringBuilder temp = new StringBuilder();
for (int i=0; i<allLines.size(); i++){
StringBuilder temp2 = new StringBuilder();
String[] abc = line.split("\t");
temp2.append("{");
temp2.append("id: \""+abc[0]+"\",");
temp2.append("name: \""+abc[1]+"\",");
temp2.append("},");
temp.append(temp2.toString());
}
System.out.println("result : "+temp.toString());
ihave code and result:
{id: "1", name: "Jhames"},{id: "2", name: "Richard"},
but i want result:
{id: "1", name: "Jhames"},{id: "2", name: "Richard"}
Just use the new java 8 StringJoiner! (And other nifty Java methods)
Example:
StringJoiner joiner = new StringJoiner(",");
joiner.add("foo");
joiner.add("bar");
joiner.add("baz");
String joined = joiner.toString(); // "foo,bar,baz"
It also supports streams in the form of Collectors.joining(",")
Full example:
public static void main(String[] args) {
String input = "1\tJames\n2\tRichard";
String output = Arrays.stream(input.split("\n"))
.map( i -> String.format("{ id: \"%s\", name: \"%s\" }", i.split("\t")))
.collect(Collectors.joining(","));
//prints: { id: "1", name: "James" },{ id: "2", name: "Richard" }
System.out.println(output);
}
You can avoid appending it in the first place :
for (int i=0; i<allLines.size(); i++){
StringBuilder temp2 = new StringBuilder();
String[] abc = line.split("\t");
temp2.append("{");
temp2.append("id: \""+abc[0]+"\",");
temp2.append("name: \""+abc[1]+"\",");
temp2.append("}");
if (i<allLines.size()-1)
temp2.append(",");
temp.append(temp2.toString());
}
Alternatively add this after your for loop
temp.setLength(temp.length() - 1);
which requires no constant index checking in your code
You can use deleteCharAt() method.
StringBuilder s = new StringBuilder("{id: \"1\", name: \"Jhames\"},{id: \"2\", name: \"Richard\"},");
System.out.println(s.deleteCharAt(s.lastIndexOf(",")));
First of all you don't need two StringBuilders, so instead of
StringBuilder sb1 = ..
for(..){
StringBuilder sb2 = ...
//fill sb2
sb1.append(sb2);
}
you should use
StringBuilder sb1 = ..
for(..){
//add all you want to sb1
sb1.append(..)
sb1.append(..)
}
Next thing is that you don't ever want to do
sb.appent("foo" + x + "bar");
because it is same as
sb.append(new StringBuilder("foo").append(x).append("bar").toString())
which is very ineffective because:
you are creating separate StringBuilder each time you do so
this new StringBuilder needs to unnecessary call toString method which has to copy all characters to new String which will later be copied to builder, instead of calling append(StringBuilder) and copy its characters directly.
So instead of sb.appent("foo" + x + "bar"); always write
sb.appent("foo").append(x).append("bar");
Now lets go back to your main problem. Since your code doesn't have declaration of line variable I am assuming that by
String[] abc = line.split("\t");
you mean
String[] abc = allLines.get(i).split("\t");
So your code can look like
StringBuilder temp = new StringBuilder();
for (int i = 0; i < allLines.size(); i++) {
String[] abc = allLines.get(i).split("\t");
temp.append("{id: \"").append(abc[0]).append("\", ");
temp.append("name: \"").append(abc[1]).append("\"}");
if (i < allLines.size() - 1)
temp.append(", ");
}
System.out.println("result : " + temp.toString());
No Java 8 solution:
StringBuilder temp = new StringBuilder();
adder(temp, allLines.get(0));
for (int i=1; i<allLines.size(); i++){
temp.append(",");
adder(temp, allLines.get(i));
}
System.out.println("result : "+temp.toString());
private static void adder(StringBuilder temp,String line){
String[] abc = line.split("\t");
temp.append("{id: \"");
temp.append(abc[0]);
temp.append("\",");
temp.append("name: \"");
temp.append(abc[1]);
temp.append("\"}");
}

How to parse the values?

I'm having a Json file like this {"Name":"Saaa","AppIcon":"ddd.jpg","Wallpaper.jpg","ddd.jpg"]}. I need to extract the AppIcon values.I'm using json simple lib to parse the json.The code snippet to parse the values is as below.
FileReader appIconReader = new FileReader("jsonpath.json");
JSONObject jsonIconObject = (JSONObject)jsonParser.parse(appIconReader);
System.out.println("APPLICATION ICON = "+jsonIconObject.get("AppIcon"));
But the output what I'm gettin is a single string as below:
["ddd.jpg","Wallpaper.jpg","ddd.jpg"]
I need to extract the individual values like this
ddd.jpg
Wallpaper.jpg
ddd.jpg
Not with the square brackets([]) and double quotes("") as I'm getting right now.How can I do that?
Try with JSON.
String str="[\"ddd.jpg\",\"Wallpaper.jpg\",\"ddd.jpg\"]";
Type collectionType = new TypeToken<String[]>() {
}.getType();
String[] a=new Gson().fromJson(str,collectionType);
for (String i:a){
System.out.println(i);
}
Output
ddd.jpg
Wallpaper.jpg
ddd.jpg
Edit: for your edited question answer like this.
public class Obj{
private String name;
private List<String> appIcons;
public List<String> getAppIcons() {
return appIcons;
}
public void setAppIcons(List<String> appIcons) {
this.appIcons = appIcons;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Now you can simply pass your JSON
String str = "{\"name\":\"Saaa\",\"appIcons\":
[\"ddd.jpg\",\"Wallpaper.jpg\",\"ddd.jpg\"]}";
Obj obj = new Gson().fromJson(str, Obj.class);
System.out.println(obj.getAppIcons());
Output:
[ddd.jpg, Wallpaper.jpg, ddd.jpg]
Assuming you have your source string:
String str = "[\"ddd.jpg\",\"Wallpaper.jpg\",\"ddd.jpg\"]";
Substring it:
str = str.substring(1, str.length() - 1);
Split it:
String[] parts = str.split(",");
Substring each part:
for(int i = 0; i < parts.length; i++) {
parts[i] = parts[i].substring(1, parts[i].length() - 1);
}
Now you have an array with each value. Note that this is unsafe, add checks before substringing.
this is what you want :
String filePath = "pathofjson\\test.json";
FileReader reader = new FileReader(filePath);
JSONParser jsonParser = new JSONParser();
try {
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
JSONArray lang= (JSONArray) jsonObject.get("AppIcon");
System.out.println(lang);
for(int i=0; i<lang.size(); i++){
System.out.println(lang.get(i));
}
} catch (org.json.simple.parser.ParseException e) {
e.printStackTrace();
}
You can use replaceAll and split
String s="[\"ddd.jpg\",\"Wallpaper.jpg\",\"ddd.jpg\"]";
String array[]=s.replaceAll("[\\[\\]\"]", "").split(","));
System.out.println(Arrays.toString(array);
replaceAll removes [ ] and " from String
split gives array of String by splitting the String with use of ,(delimeter)
Arrays.toString used to print Array.
OUTPUT
[ddd.jpg, Wallpaper.jpg, ddd.jpg]
With JSON you can try this
String s="{\"Name\":\"Saaa\","+
" \"AppIcon\":[\"ddd.jpg\",\"Wallpaper.jpg\",\"ddd.jpg\"]}";
org.json.JSONObject json=new org.json.JSONObject(s);
org.json.JSONArray jarray=json.getJSONArray("AppIcon");
System.out.println(jarray.get(0));//Will give ddd.jpg
//Iterate over array to get all
Try this :
String str = "[\"ddd.jpg\",\"Wallpaper.jpg\",\"ddd.jpg\"]";
String tempStr = str.replaceAll("\\W{2,}", ",");
String substring = tempStr.substring(1, tempStr.length() -1);
String[] strArray = substring.split(",");
You should use java.util.StringTokenizer
String s = "[\"ddd.jpg\",\"Wallpaper.jpg\",\"ddd.jpg\"]";
StringTokenizer tokenizer = new StringTokenizer(s, "[\",]");
while (tokenizer.hasMoreElements()) {
System.out.println(tokenizer.nextElement());
}
Here you have a possible solution:
String data = "{\"Name\":\"Saaa\",\"AppIcon\":[\"ddd.jpg\",\"Wallpaper.jpg\",\"ddd.jpg\"]}";
data = data.replaceAll("(.*\"AppIcon\":\\[)(.+)(\\].*)", "$2");
data = data.replaceAll("\"", "");
for(String str: data.split(",")) {
System.out.println(str);
}
which only involves the String class explicitly, and works for every String which the format defined in the question (which has "AppIcon:[]").
Following the description this is what you asked for:
String s = "[\"ddd.jpg\",\"Wallpaper.jpg\",\"ddd.jpg\"," +
"\"Wallpaper.jpg\",\"ddd.jpg\"," +
"\"Wallpaper.jpg\",\"ddd.jpg\"]";
String [] almost_the_words = s.split("\",\"");
int l = almost_the_words.length;
ArrayList<String> words = new ArrayList<String>();
String temp1 = almost_the_words[0].split("\"")[1];
String temp2 = almost_the_words[l-1].split("\"")[0];
words.add(temp1);
for(int i=1; i< l-1; i++) {
words.add(almost_the_words[i]);
}
words.add(temp2);
for(String w : words) {
System.out.println(w);
}
EDIT:
Parse a JSON File with those Strings using GSON:
import java.util.ArrayList;
public class MyObject {
ArrayList<String> appicon;
public MyObject(ArrayList<String> appicon) {
super();
this.appicon = appicon;
}
public ArrayList<String> getAppicon() {
return appicon;
}
public void setAppicon(ArrayList<String> appicon) {
this.appicon = appicon;
}
}
Use the class "MyObject" with the Library GSON: https://code.google.com/p/google-gson/

Split mathematical string in Java

I have this string: "23+43*435/675-23". How can I split it? The last result which I want is:
String 1st=23
String 2nd=435
String 3rd=675
String 4th=23
I already used this method:
String s = "hello+pLus-minuss*multi/divide";
String[] split = s.split("\\+");
String[] split1 = s.split("\\-");
String[] split2 = s.split("\\*");
String[] split3 = s.split("\\/");
String plus = split[1];
String minus = split1[1];
String multi = split2[1];
String div = split3[1];
System.out.println(plus+"\n"+minus+"\n"+multi+"\n"+div+"\n");
But it gives me this result:
pLus-minuss*multi/divide
minuss*multi/divide
multi/divide
divide
But I require result in this form
pLus
minuss
multi
divide
Try this:
public static void main(String[] args) {
String s ="23+43*435/675-23";
String[] ss = s.split("[-+*/]");
for(String str: ss)
System.out.println(str);
}
Output:
23
43
435
675
23
I dont know why you want to store in variables and then print . Anyway try below code:
public static void main(String[] args) {
String s = "hello+pLus-minuss*multi/divide";
String[] ss = s.split("[-+*/]");
String first =ss[1];
String second =ss[2];
String third =ss[3];
String forth =ss[4];
System.out.println(first+"\n"+second+"\n"+third+"\n"+forth+"\n");
}
Output:
pLus
minuss
multi
divide
Try this out :
String data = "23+43*435/675-23";
Pattern pattern = Pattern.compile("[^\\+\\*\\/\\-]+");
Matcher matcher = pattern.matcher(data);
List<String> list = new ArrayList<String>();
while (matcher.find()) {
list.add(matcher.group());
}
for (int index = 0; index < list.size(); index++) {
System.out.println(index + " : " + list.get(index));
}
Output :
0 : 23
1 : 43
2 : 435
3 : 675
4 : 23
I think it is only the issue of index. You should have used index 0 to get the split result.
String[] split = s.split("\\+");
String[] split1 = split .split("\\-");
String[] split2 = split1 .split("\\*");
String[] split3 = split2 .split("\\/");
String hello= split[0];//split[0]=hello,split[1]=pLus-minuss*multi/divide
String plus= split1[0];//split1[0]=plus,split1[1]=minuss*multi/divide
String minus= split2[0];//split2[0]=minuss,split2[1]=multi/divide
String multi= split3[0];//split3[0]=multi,split3[1]=divide
String div= split3[1];
If the order of operators matters, change your code to this:
String s = "hello+pLus-minuss*multi/divide";
String[] split = s.split("\\+");
String[] split1 = split[1].split("\\-");
String[] split2 = split1[1].split("\\*");
String[] split3 = split2[1].split("\\/");
String plus = split1[0];
String minus = split2[0];
String multi = split3[0];
String div = split3[1];
System.out.println(plus + "\n" + minus + "\n" + multi + "\n" + div + "\n");
Otherwise, to spit on any operator, and store to variable do this:
public static void main(String[] args) {
String s = "hello+pLus-minuss*multi/divide";
String[] ss = s.split("[-+*/]");
String plus = ss[1];
String minus = ss[2];
String multi = ss[3];
String div = ss[4];
System.out.println(plus + "\n" + minus + "\n" + multi + "\n" + div + "\n");
}

Categories

Resources