【问题标题】:Splitting a String for use in a UI selection element [duplicate]拆分字符串以在 UI 选择元素中使用 [重复]
【发布时间】:2014-03-22 00:43:48
【问题描述】:

我还在学习 Java。我有这个 XML 字符串数组列表:

<string-array name="CountryCodes" >
 <item>93,AF, Afganistan</item>
 <item>355,AL, Albania</item>
 <item>213,DZ, Algeria</item>
</string-array>

我正在使用 Arrayadapter 将此数组添加到这样的微调器中:

String [] countries = this.getResources().getStringArray(R.array.CountryCodes);


        ArrayAdapter<String> adapter =  new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, countries);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

         mCountries.setAdapter(adapter);

这很好用,XML 没有问题,但我真正想做的是在微调器中只显示国家,然后在单独的 Edittext 中显示相应的数字。

我知道我必须使用split() 方法来删​​除","。但是一旦我有了单独的字符串元素(例如“93,AF,Afganistan”)

我该怎么做

  1. 只获取国家/地区名称
  2. 保持国家名称与相应数字同步

【问题讨论】:

  • @Simon 不是重复的,因为xml解析是android作为资源完成的,而且String[]已经存在了。
  • @user28... :您需要使用 String.split(",") 拆分字符串并使用位置 2 的项目(加上修剪)。
  • @njzk2 谢谢。这很有帮助。现在我明白了 BradR 的回答。
  • @njzk2 嗯,我想我已经添加了评论。我的观点是,在 XML 上使用任何字符串方法都注定要失败。改用解析器,然后对解析出的数据执行字符串操作。我们不要再开启地狱之门stackoverflow.com/questions/1732348/…
  • @Simon:是的,但这实际上与 XML 无关。 Android 会为您完成所有解析 (getResources().getStringArray),SO 真正在处理的是字符串数组,正如您在 BradR 的回答中看到的那样。

标签: java android arrays substring


【解决方案1】:

如果你想将国家名称从给定的数组中分离出来,你可以使用这样的东西。

    String[] edited = new String[countries.length];
    for(int i = 0; i < countries.length; i++) {
        String s = countries[i];
        edited[i] = s.substring(s.lastIndexOf(','));
    }

【讨论】:

    【解决方案2】:

    这将使用拆分 mycoutries 将只有国家和 myotherstuff 来自该行的其余数据

    String[] mycountries= new String[countries.length];
    String[] myotherstuff = new String[countries.length];
     for(int i = 0; i < countries.length; i++) {
        String s = countries[i];
        String[] parts = s.split(","); 
        myotherstuff[i] = parts[0]+","+parts[1];
        mycountries[i] = parts[2];
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-23
      • 1970-01-01
      • 2012-10-02
      • 1970-01-01
      • 2020-01-07
      • 1970-01-01
      • 2021-08-06
      • 1970-01-01
      相关资源
      最近更新 更多