Monday, October 12, 2015

java - How to convert a string to a char array

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.RelativeLayout;
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
        RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);
        TextView tv = (TextView) findViewById(R.id.tv);

        // Empty the TextView
        tv.setText("");

        // Initialize a new string variable
        String alphabet = "ABCDEFGH";
        tv.setText("String : " + alphabet);

        // Convert the String to char array
        char[] charactersOfAlphabet = alphabet.toCharArray();

        tv.setText(tv.getText() + "\nchar array elements : ");
        // Iterate over the char array
        for(int i=0;i<charactersOfAlphabet.length;i++){
            tv.setText(tv.getText() +""+ charactersOfAlphabet[i] + ", ");
        }
   }
}
More android examples