String joining with delimiter not working in Android - java

I am trying to convert string array into string and join all values with delimiter (,) but it is adding only first two values, what is wrong in conversion code. Please see inline comments below
String[] array = new String[20];
for (int i = 0; i <= count; i++) {
Log.d(TAG, "arrayvalue : " + array[i]); //Here I will get 5 values which is exact value count, but in next converted log I will have concatenation of only first two values, what is wrong in conversion code.
// Joining:
StringBuilder buffer = new StringBuilder();
for (String each : array)
buffer.append(",").append(each);
String joined = buffer.deleteCharAt(0).toString();
Log.d("Prefs", "Converted Array to String : " + joined);
}

There is standard method for String join defined in Android SDK:
final String joined = TextUtils.join(",", array);

Use in dynamic array
String[] partno = new String[part.size()];
for(int i = 0; i < part.size(); i++){
partno[i]=part.get(i).getText().toString();
Hpartno= TextUtils.join(",",partno);
}

Related

break large String into small Strings

i have a large string which contains Id's example :
HD47-4585-GG89
here at the above i have an id of a single object but sometimes it may contain id's of multiple objects like this :
HD47-4585-GG89-KO89-9089-RT45
the above haves ids of 2 objects now i want to convert the above string to an array or in multiple small Strings
something like :
id1 = HD47-4585-GG89
id2 = KO89-9089-RT45
every single id haves a fixed number of characters in it here its 14 (counting the symbols too) and the number of total id's in a single String is not determined
i dont know how to do it any one can guide me with this ?
i think all i have to do is clip the first 14 characters of string then assign a variable to it and repeat this until string is empty
You could also use regex:
String input = "HD47-4585-GG89-KO89-9089-RT45";
Pattern id = Pattern.compile("(\\w{4}-\\w{4}-\\w{4})");
Matcher matcher = id.matcher(input);
List<String> ids = new ArrayList<>();
while(matcher.find()) {
ids.add(matcher.group(1));
}
System.out.println(ids); // [HD47-4585-GG89, KO89-9089-RT45]
See Ideone.
Although this assumes that each group of characters (HD47) is 4 long.
Using guava Splitter
class SplitIt
{
public static void main (String[] args) throws java.lang.Exception
{
String idString = "HD47-4585-GG89-KO89-9089-RT45-HD47-4585-GG89";
Iterable<String> result = Splitter
.fixedLength(15)
.trimResults(CharMatcher.inRange('-', '-'))
.split(idString);
String[] parts = Iterables.toArray(result, String.class);
for (String id : parts) {
System.out.println(id);
}
}
}
StringTokenizer st = new StringTokenizer(String,"-");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
these tokens can be stored in some arrays and then using index you can get required data.
String text = "HD47-4585-GG89-KO89-9089-RT45";
String first = "";
String second = "";
List<String> textList = Arrays.asList(text.split("-"));
for (int i = 0; i < textList.size() / 2; i++) {
first += textList.get(i) + "-";
}
for (int i = textList.size() / 2; i < textList.size(); i++) {
second += textList.get(i) + "-";
}
first = first.substring(0, first.length() - 1);
second = second.substring(0, second.length() - 1);

Separating the int values based on the occurrance of sequence of the values in java?

i have an integer values as:
1299129912
i want to store it as
12
12
12
in the int v1,v2,v3;
i.e.,when ever 9909 occurs we need to separate the values individually. Is it possible in java. If so please anyone help me.
here is the code I'm trying
int l = 1299129912;
Pattern p = Pattern.compile("99");
Matcher m1 = p.matcher(l);
if (m1.matches()) {
System.out.println("\n");
}
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method matcher(CharSequence) in the type Pattern is not applicable for the arguments (int)
I suppose you already have the value as a String since 1234990912349909 is more that Integer.MAX_VALUE. Then you can split the string into String[] and do whatever you want with the separate values. E.g. call parseInt on each element.
String[] values = myIntString.split("9909");
for (String value: values) {
int v = Integer.parseInt(value);
}
Yes, it is very possible in java. Just convert the integer to a string and replace the 9909 with a space.
Example:
String s="1234990912349909";
s=s.replaceAll("9909","");
int a=Integer.parseInt(s);
System.out.println(a);
//output would be 12341234
If you know you are always going to have 3 integers named v1, v2, and v3 the following would work:
String[] numbers = l.toString().split("99");
int v1 = Integer.parseInt(numbers[0]);
int v2 = Integer.parseInt(numbers[0]);
int v3 = Integer.parseInt(numbers[0]);
However if you don't know in advance then it might be better to do it like this:
String[] numbers = l.toString().split("99");
int[] v = new int[numbers.length];
for (int i = 0; i < numbers.length; i++)
v[i] = Integer.parseInt(numbers[i]);
I found out this is the easiest way to show you how you can resolve your issue:
I included clear comments on every important step. Please check this:
int num = 1239012390;
// Convert int into a string
String str = String.valueOf(num);
// What separates the values
String toBremoved = "90";
String str1 = "";
// Declare a String array to store the final results
String[] finalStrings = new String[2];
// i will be used as an index
int i = 0;
do {
// Finds and separates the first value into another string
finalStrings[i] = str.substring(0, str.indexOf(toBremoved));
// removes the first number from the original string
str = str.replaceFirst(finalStrings[i], "");
// Remove the next separating value
str = str.replaceFirst(str.substring(str.indexOf(toBremoved), str.indexOf(toBremoved) + toBremoved.length()), "");
// increments the index
i++;
} while (str.indexOf(toBremoved) > 0); // keeps going for a new iteration if there is still a separating string on the original string
// Printing the array of strings - just for testing
System.out.println("String Array:");
for (String finalString : finalStrings) {
System.out.println(finalString);
}
// If you want to convert the values into ints you can do a standard for loop like this
// Lets store the results into an int array
int [] intResults = new int [finalStrings.length];
for (int j = 0; j < intResults.length; j++) {
intResults[j] = Integer.valueOf(finalStrings[j]);
}
// empty line to separate results
System.out.println();
// Printing the array of ints
System.out.println("int Array:");
for (int intResult : intResults) {
System.out.println(intResult);
}
Or in a simplified and more accurate way:
(you can use the example above if you need to understand how it can be done the long way)
int num = 1239012390;
String [] numbers = String.valueOf(num).split("90");
int num1 = Integer.parseInt(numbers[0]);
int num2 = Integer.parseInt(numbers[1]);
System.out.println("1st -> " + num1);
System.out.println("2nd -> " + num2);

Java: return 2D Array with very varying entry lengths as formatted string

I want to write a toString method for a Matrix class where I need to return a formatted string which contains the matrix. The entries in the matrix are very different in length so just separating the entries with a TAB doesn't the trick. Right now I have the following:
public String toString(){
String str = "";
for(int i=0;i < _dim[0];i++){
for(int j=0;j < _dim[1];j++){
str += this.values[i][j] + "\t" + "\t";
}
str += "\n";
}
return str;
}
Which gives me something like this.
3.2004951E7 -1.591328E7 17839.0
-35882.0 17841.0 -20.0
1794.0 -892.0 1.0
Is there a way to print these properly aligned without knowing in advance how long each entry is going to be?
Thanks.
Is there a way to print these properly aligned without knowing in
advance how long each entry is going to be?
I don't think there is any built-in library function available which can do such things
for us. We will have to make our own formatting such as, using: %-xs:
Create an one dimensional array: maxWidth[col] to find the maximum width of each column: the column size is equal to the number of column of the 2D array.
Visit the 2D array to find the maximum width of each column
create the formatting string for each column using "%-"+maxWidth[col]+"s ", where - after the % specifies formatting for left-justified.
Please check out the formatting Numeric Print Output for more details.
The sample code:
String data[][] = {{3.2004951E7+"" , -1.591328E7+"", 17839.0+"" },
{-35882.0 +"" , -17841.0+"", -20.0+"" }};
int col = data[0].length;
int row = data.length;
int maxWidth[] = new int[col];
for(String[] rowD : data)
for(int i=0; i< col; i++)
{
if(maxWidth[i] < rowD[i].length())
maxWidth[i] = rowD[i].length();
}
String format = "";
for(int x : maxWidth)
format += "%-"+(x+2)+"s ";
format +="%n";
System.err.println(format);
for(String[] rowD : data)
{
System.out.printf(format, rowD);
}
Output:
3.2004951E7 -1.591328E7 17839.0
-35882.0 -17841.0 -20.0
You can use String.format() if you know the length of your longest String, let's call it maxLength.
public String toString(){
String str = "";
for(int i=0;i < _dim[0];i++){
for(int j=0;j < _dim[1];j++){
String value = String.valueOf(this.values[i][j]);
str += String.format("%1$-" + (max-value.length()) + "s", " ") + value + "\t";
}
str += "\n";
}
return str;
}

String Array to String [duplicate]

This question already has answers here:
How to convert an int array to String with toString method in Java [duplicate]
(8 answers)
Closed 9 years ago.
I am trying to take an arbitrary-length String[] and print it out to a String, preferably with field separators. Right now I have:
String[] start = {"first", "second", "third"}; //[] to convert
String cC = "";
String finish = ""; // Final String
String cC1 = "";
{
for (int i = 0; i < puts.length; i++) {
cC = puts[i] + ", ";
cC1 = (finish + cC);
finish = cC1;
}
}
But for some reason it is only returning the "second" value. How can I make it properly concatenate the values?
Also, could I simplify the code by using finish += cC? Thanks.
String[] start = {"first", "second", "third"};
String addedTogether = Arrays.toString(start);
System.out.println(addedTogether);
//prints [first, second, third]
If You want to append to a string you should use +=
e.g.
String[] start = {"first", "second", "third"};
String cc = "";
String separator = ",";
for (int i = 0; i < start.length; i++) {
cc += start[i];
//Not Add , if it is the last element.
if(i!=start.length-1){
cc+=separator;
}
}
etc.
with your way you are setting the last value to finish.
String[] start = {"first", "second", "third"}; //[] to convert
String finish = ""; // Final String
{
for (int i = 0; i < starts.length; i++) {
finish = finish + start[i] + ", ";
}
}
(If you wanted to do all this manually for some reason...)
Check out -- Java equivalents of C# String.Format() and String.Join()
That provides a string.join method, as well as some reading on useful string utility methods.
It is a very bad idea to concatenate Strings using += operator. It is always better to construct StringBuilder object and append all the values to it. And lastly call toString() on the StringBuilder object.
Take a look at this link to understand the performance hit associated with using + operator for string concatenation.
http://blog.eyallupu.com/2010/09/under-hood-of-java-strings.html
How Java do the string concatenation using "+"?

Split long string into byte arrays

This is for the level system in a game.
The level consists of two byte arrays:
byte[] tiles and byte[] data
tiles holds the id of the tiles and data holds data.
I created a function to make a string out of them. It's formatted like tileId:tileData,tileId:tileData,tileId:tileData,etc
You can see an example of a complete level here: http://pastebin.com/X2LG7e80
The script looks like this:
public String toString() {
String s = "";
StringBuilder sb = new StringBuilder();
for (int t = 0; t < tiles.length; t++) {
sb.append(tiles[t]).append(":").append(data[t]).append(t == tiles.length - 1 ? ";" : ",");
}
s = sb.toString();
return s;
}
Now I need a way to turn it back into two byte arrays.
I tried a couple of different things but none of them worked.
Assuming a variable stringRep contains the string representation:
String stringRep = "tileId:tileData,tileId:tileData,tileId:tileData";
String[] pairs = stringRep.split(",");
byte[] tiles = new byte[pairs.length];
byte[] data = new byte[pairs.length];
int i = 0;
for(String pair : pairs){
String[] pairParts = pair.split(":");
titles[i] = Byte.parseByte(pairParts[0]);
data[i] = Byte.parseByte(pairParts[1]);
i++;
}

Categories

Resources