Monday, October 12, 2015

java - How to split a comma delimited string into array

MainActivity.java

package com.cfsuman.me.javaexamples;

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


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);

        // Initialize a new string
        String stringOfColors = " Red,Green,,  ,   Yellow, Black ";

        // Display the string
        tv.setText("String :" + stringOfColors);

        // Split the String by comma delimiter and generate an string array
        String[] colorsArray = stringOfColors.split(",");

        tv.setText(tv.getText() + "\nArray :");
        // Iterate over the String array
        for(int i=0;i<colorsArray.length;i++){
            tv.setText(tv.getText() +""+ colorsArray[i] + "+");
        }

        // Split the String by comma delimiter and generate an string array
        // Also remove the white spaces from elements
        String[] colorsArrayWithoutSpaces = stringOfColors.split("\\s*,\\s*");

        tv.setText(tv.getText() + "\nArray (remove white spaces):");
        // Iterate over the String array
        for(int i=0;i<colorsArrayWithoutSpaces.length;i++){
            tv.setText(tv.getText() +""+ colorsArrayWithoutSpaces[i] + "+");
        }

        // Also remove the string leading and trailing white spaces
        String[] colorsArrayWithoutSpaces2 = stringOfColors.trim().split("\\s*,\\s*");

        tv.setText(tv.getText() + "\nArray (remove all white spaces):");
        // Iterate over the String array
        for(int i=0;i<colorsArrayWithoutSpaces2.length;i++){
            tv.setText(tv.getText() +""+ colorsArrayWithoutSpaces2[i] + "+");
        }

        // Remove all white spaces and remove empty elements
        // Using regular expression to perform task
        String[] arrayWithoutEmptyElements = stringOfColors.replaceAll("^[,\\s]+", "").split("[,\\s]+");

        tv.setText(tv.getText() + "\n\nFinally, you can split this way");
        tv.setText(tv.getText() + "\nArray (remove empty elements):");
        // Iterate over the String array
        for(int i=0;i<arrayWithoutEmptyElements.length;i++){
            tv.setText(tv.getText() +""+ arrayWithoutEmptyElements[i] + "+");
        }
    }
}
More android examples