Monday, October 12, 2015

java - How to split string into array of character strings

MainActivity.java

package com.cfsuman.me.javaexamples;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Window;
import android.widget.TextView;


public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_ACTION_BAR);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Set background color for action bar
        getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.RED));

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

        // Initialize a new string variable
        String alphabet = "ABCD";

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

        // Split the String and generate a String array
        String[] splitString = alphabet.split("");

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

        // Perfect way to split a string to array of character strings
        // String split by using regular expression
        String[] letters = alphabet.split("(?!^)");

        tv.setText(tv.getText() + "\n\nCorrect way to split string to letters");
        tv.setText(tv.getText() + "\nString array length : " + letters.length);
        tv.setText(tv.getText() + "\nString array (split - regular expression) : ");
        // Iterate over the String array
        for(int i=0;i<letters.length;i++){
            tv.setText(tv.getText() +""+ letters[i] + ", ");
        }
  }
}
More android examples