Tuesday, October 13, 2015

java - How to convert an array to a string

MainActivity.java

package com.cfsuman.me.javaexamples;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import java.util.Arrays;


public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get widget reference from XML layout
        TextView tv = (TextView) findViewById(R.id.tv);

        // Initializing a new String array
        String[] colors = new String[]{"Red","Green","Yellow","Black"};

        tv.setText("String array : ");
        // Iterate through the array
        for(int i=0;i<colors.length;i++){
            tv.setText(tv.getText() + colors[i]+", ");
        }

        // Convert the array to a String object
        String colorsString = Arrays.toString(colors);
        tv.setText(tv.getText() + "\nString (direct convert) : " + colorsString);

        // Create a String from array elements by adding them manually
        colorsString ="";
        for(int i=0;i<colors.length;i++){
            colorsString +=colors[i];
        }
        tv.setText(tv.getText() + "\nString (by loop) : " + colorsString);

        // Create a String from array elements by adding them manually
        // Use a custom separator
        colorsString ="";
        for(int i=0;i<colors.length;i++){
            colorsString +=colors[i] + " | ";
        }
        tv.setText(tv.getText() + "\nString (loop and separator): " + colorsString);

        // Create a String from array elements using StringBuilder
        StringBuilder builder = new StringBuilder();
        for(int i=0;i<colors.length;i++){
            builder.append(colors[i]);
        }
        tv.setText(tv.getText() + "\nString (loop and StringBuilder): " + builder.toString());

        // Create a String from array elements using StringBuilder
        builder.setLength(0); // Empty the StringBuilder
        for(int i=0;i<colors.length;i++){
            builder.append(colors[i]);
            builder.append(" : "); // Add a separator for array each element
        }
        tv.setText(tv.getText() + "\nString (loop and StringBuilder): " + builder.toString());

        // Initialize a new int array
        int[] result = new int[]{10,20,30,40,50};

        tv.setText(tv.getText() + "\n\nInt array : ");
        // Iterate through the int array
        for(int i=0;i<result.length;i++){
            tv.setText(tv.getText() + "" +result[i]+", ");
        }

        // Convert int array to a String object
        String resultString = Arrays.toString(result);

        // Display the converted String object
        tv.setText(tv.getText() + "\nString (direct convert): " + resultString);
    }
}
More android examples