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] + "+"); } } }
- java - How to convert an array to a list
- java - How to check if an array contains a certain value
- java - How to iterate through a HashMap
- java - How to initialize an ArrayList
- java - How to iterate through an ArrayList
- java - How to sort an ArrayList
- java - How to concatenate two arrays
- java - How to convert a string to a byte array
- java - How to split string into array of character strings
- java - How to convert string to double
Komentar
Posting Komentar