【问题标题】:search exact string in string array?在字符串数组中搜索确切的字符串?
【发布时间】:2023-03-13 21:10:01
【问题描述】:

我有一个旋转器。我想获取所选项目的值并在另一个数组中搜索该值的索引。 这是我到目前为止所尝试的。 s1 是微调器。武器是我要在微调器 s1 中搜索所选项目的值的数组

String[] weaponone = getResources().getStringArray(R.array.weapons);
for (String s : weaponone) {
    int i = s.indexOf(s1.getSelectedItem().toString());
    switch (i) {
        case (0):

【问题讨论】:

  • 我不明白这个问题..?
  • 你说你在你的字符串数组中寻找一个精确的字符串你没有为你在你的数组中搜索的值定义任何常量你在一个 int 上做一个 switch case而不是字符串 ..
  • 在第一行我正在定义数组,我想在其中比较通过在第三行中选择微调器 s1 上的项目得到的字符串。
  • 请解释您的问题并说明您需要什么,尽量直截了当。
  • 您遇到什么问题了吗?

标签: java android arrays string


【解决方案1】:

好的,我知道你的情况......在你的情况下,不需要使用 foreach 循环专注于以下示例.. 首先在res/values 文件夹下获取一个arrays.xml 文件 并像这样声明weapons数组

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string-array name="weapons">
        <item>a</item>
        <item>b</item>
        <item>c</item>        
    </string-array>

</resources>

你的java代码看起来像这样

String[] weaponone = getResources().getStringArray(R.array.weapons);

    int i= Arrays.asList(weaponone).indexOf("b");   //i=1 for b, for a i=0 and for c i=2,if not found then i=-1 
        switch (i) {
            case (0):
               // implement your code 
                break;
            case (1):
               // implement your code 
                break;
            case (2):
               // implement your code 
                break;

           .................................


            case (-1):// when not matching 
               // implement your code 
                break;
        }

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-04
    • 2020-02-01
    • 2020-02-27
    • 1970-01-01
    • 1970-01-01
    • 2018-06-10
    • 1970-01-01
    相关资源
    最近更新 更多