本文实例为大家分享了Android split分割特殊字符取名称的具体实现代码,供大家参考,具体内容如下
一、布局
<?xml version="1.0" encoding="utf-8"?>
<layout>
<data class="NewBer">
</data>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".MainActivity">
<Button
android:id="@+id/bt_back"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="获取名字"
>
</Button>
</RelativeLayout>
</layout>
二、实体类(MainActivity)
public class MainActivity extends Activity {
private NewBer dataBinding;
String list="张三|3728478,李四|98956265,王五|6233265,赵六|56221456";
String as="";
private String substring;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
//点击获取名称
dataBinding.btBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//从大到小,先分割逗号(,)随后在分割特殊字符(|) 注:(|)一定要加上前面的两个(\\)
String[] split = list.split(",");
for (int i = 0; i < split.length; i++) {
String[] split2 = split[i].split("\\|");
for (int j = 0; j < split2.length; j++) {
//取(偶数)|前面名字,取(奇数)j%2!=0为|后面的数字
if (j%2==0){
as += split2[j]+",";
//分割最后的逗号(,)
if (0 < as.length()-1){
substring = as.substring(0, as.length()-1);
}
Log.i("TAG",substring); //输出结果:张三,李四,王五,赵六
dataBinding.btBack.setText(substring);
}
}
}
}
});
}
}
三、效果图