【问题标题】:How to add alternate elements to a String array如何将备用元素添加到字符串数组
【发布时间】:2023-03-03 03:13:01
【问题描述】:

我有一个字符串 - “Hello@World@Good@Morning”

我想在字符串数组中添加替代词。例如,从上面的字符串中,我应该只将 Hello 和 good 添加到我的新数组中。

for (String s   : StringsTokens) {
            myStringArray = s.split(Pattern.quote("@"));

        }

如何只将备用元素添加到字符串数组。

【问题讨论】:

  • 你能把你的代码分享为minimal, complete, verifiable example吗?
  • 备用元素是具有索引i 的元素,例如:i%2 == 0....
  • 使用for (int i = 0 ; i < SringsTokens.lenght ; i++) { // do your test here : if(i%2 == 0) then add the element to your array

标签: java arrays


【解决方案1】:

查看模式,您需要添加位于偶数位置的单词。

所以用下面的代码分割字符串后,得到一个字符串数组:

String[] words = string.split("@");

并初始化一个 ArrayList 以在您的循环中使用:

ArrayList<String> arList = new ArrayList<>();

您将运行 for 循环:

for (int i=0 ; i<words.length ; i+=2) {
     // store the words in ArrayList like
     arList.add(words[i]);
}
//Convert ArrayList to Array and re-initialise ArrayList for the next String
String[] newArray = arList.toArray();
arList = new ArrayList<String>();

【讨论】:

    【解决方案2】:

    试试这个:

            List<String> result = new ArrayList<>();
            String[] src = "Hello@World@Good@Morning".split( "@" );
            for ( int i=0 ; i < src.length ; i++ ) {
                if( i%2 == 0 ) {
                    result.add( src[i] );
                }
            }
            System.out.println(result);
    

    输出:[你好,很好]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多