【问题标题】:How to add new Strings to a certain array如何将新字符串添加到某个数组
【发布时间】:2013-04-07 18:22:26
【问题描述】:

我的代码中有 4 个数组,每次用户向 edittext 写入内容时,我想将该字符串存储在其中一个数组中,我尝试使用 toCharArray 方法,但我不知道如何定义数组字符串应该放在 :S

String [] array7 = {"Hey","Was Up","Yeahh"};
    TextView txtV1,txtV2;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layouttry);
        txtV1=(TextView)findViewById(R.id.textView1);
        txtV2=(TextView)findViewById(R.id.textView2);



        Bundle extras = getIntent().getExtras();
        String value = extras.getString("Key");  // this value I want to add to the stringarray

【问题讨论】:

  • 一些代码肯定会让这个问题变得有意义。
  • 谢谢 :) 这很有帮助!!
  • 他是认真的。您的问题不清楚,请将您的代码复制并粘贴到问题中,或者至少尝试更具体一些 - 数组是什么类型,您将如何决定每个字符串的数组等等。
  • 您不知道谁否决了您的问题。可能是别人。它是本网站的一部分,发生在每个人身上。甚至我... :)

标签: java android arrays string add


【解决方案1】:

如果您需要添加新元素,我建议您将数组替换为 ArrayLists。这将允许您使用add 方法插入新元素。一个例子:

ArrayList<String> stringList = new ArrayList<String>();
stringList.add("Text here");

【讨论】:

    【解决方案2】:

    在您的代码中,我只能在字符串上看到一个数组,所以我不确定您实际需要什么。不过我会努力的。

    您的字符串数组被硬编码为只有三个单元格,而且它们都是满的。如果你想把字符串放到这些地方,这样做:

    array7[0] = value; //or:
    array7[1] = value; //or:
    array7[1] = value;
    

    如果您想将value 添加到数组而不删除现有值,您可以执行以下操作:

    //Create a new array, larger than the original.
    String[] newArray7 = new String[array7.length + 1 /*1 is the minimum you are going to need, but it is better to add more. Two times the current length would be a good idea*/];
    
    //Copy the contents of the old array into the new one.
    for (int i = 0; i < array7.length; i++){
       newArray7[i] = array7[i];
    }
    
    //Set the old array's name to point to the new array object.
    array7 = newArray7;
    

    您可以在单独的方法中执行此操作,因此当您需要重新调整数组大小时,您可以使用它。你应该知道 ArrayList 和 Vector 类已经为你实现了这个机制,你可以随意arrayList.add(string)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多