在java中引用数组中的值

Sim*_*eon 4 java eclipse android

使用Java拆分简单数组时,如何在不使用println的情况下引用特定值?

我有一个字符串分隔"||"- 我想操纵该字符串,以便我可以调用它的每一半并将每个位分配给一个新的字符串.如果这是php我会使用list()或explode(),但我似乎无法让变量工作.

我想要

  1. 将每一半临时数组的内容输出到屏幕和
  2. 加入这些部分message = temp[0]+ "-"+ temp[1];似乎不起作用.
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); 
}
Run Code Online (Sandbox Code Playgroud)

Psh*_*emo 7

乍一看,似乎你的问题就在这里

String delimiter = "||";
String[] temp = message.split(delimiter);
Run Code Online (Sandbox Code Playgroud)

因为split使用正则表达式作为参数而在正则表达式中|是特殊字符表示OR.所以||你拆分:空字符串""或空字符串""或空字符串"".
由于空字符串始终位于每个字符之前,并且在字符结果之后"abc".split("||")将被分割(例如["", "a", "b", "c"],默认情况下删除的最后一个空字符串将从结果数组中删除).

要解决这个问题,你必须逃脱|.您可以通过在此元字符之前放置\(在Java中需要编写为"\\")来执行此操作,或者您可以使用它Pattern.quote(regex)来regex为您转义所有元字符.尝试

String delimiter = "||";
String[] temp = message.split(Pattern.quote(delimiter));
Run Code Online (Sandbox Code Playgroud)