When splitting a simple array using Java, how can I reference the specific values without using println?
I have a string separated by "||"
- I want to manipulate that string such that I can call each half of it and assign each bit to a new string. If this was php I'd use list() or explode(), but I can't seem to get the variables to work.
I want to
message = temp[0]+ "-"+ temp[1];
doesn't seem to work.protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// Show the Up button in the action bar.
getActionBar().setDisplayHomeAsUpEnabled(true);
}
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.SENTMESSAGE);
//The string is (correctly) submitted in the format foo||bar
String delimiter = "||";
String[] temp = message.split(delimiter);
//??? How do I output temp[0] and temp[1] to the screen without using println?
//This gives me a single character from one of the variables e.g. f-
for(int i =0; i < temp.length ; i++)
message = temp[0]+ "-"+ temp[1];
//if I escape the above 2 lines this shows foo||bar to the eclipse screen
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
}
At fist glance it seems that your problem is here
String delimiter = "||";
String[] temp = message.split(delimiter);
because split
uses regex as parameter and in regex |
is special character representing OR
. So with ||
you split on: empty String ""
OR empty string ""
OR empty String ""
.
Since empty String is always before each character and after character result of split such as "abc".split("||")
will be ["", "a", "b", "c"]
(last empty Strings by default removed are removed from result array).
To solve this problem you will have to escape |
. You can do it by placing \
(which in Java needs to be written as "\\"
) before this metacharacter or you can just use Pattern.quote(regex)
to escape all regex
metacharacters for you. Try
String delimiter = "||";
String[] temp = message.split(Pattern.quote(delimiter));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With