简体   繁体   English

如何将字符串插入字符串数组中的特定索引并在此之后移动字符串?

[英]How to Insert string to a particular index in string array and shifting strings after that?

I have a code like following 我有一个像下面的代码

String singlestr="hello|world|how|are|you";
String[] arraystr = singlestr.split("|");

and as result i have => 结果我有=>

arraystr[0]=hello
arraystr[1]=world
arraystr[2]=how
arraystr[3]=are
arraystr[4]=you

Now the problem is how can i insert a new string to 3rd postion? 现在的问题是,如何在第3个位置插入新字符串? is there any functions? 有什么功能吗?

Expected output after inserting a new string to index 2: 在索引2中插入新字符串后的预期输出:

arraystr[0]=hello
arraystr[1]=world
arraystr[2]=hi
arraystr[3]=how
arraystr[4]=are
arraystr[5]=you

Try using a StringBuilder. 尝试使用StringBuilder。 Use the append() method to insert the elements from arrayStr, then use insert() to insert new text at the desired location. 使用append()方法从arrayStr插入元素,然后使用insert()在所需位置插入新文本。 The toString() method will return the finished string. toString()方法将返回完成的字符串。

My example code assumes you know the exact insertion point for the new text. 我的示例代码假定您知道新文本的确切插入点。 A more general method would use the indexOf() method to get the offset of the text following your insertion point, then use that index as the offset argument in the call to insert(). 更通用的方法是使用indexOf()方法获取插入点后的文本的偏移量,然后在调用insert()时将索引用作偏移量参数。 Also, your example splits the initial string into separate words with no embedded separators. 另外,您的示例将初始字符串拆分为没有嵌入式分隔符的单独单词。 toString() would return "helloworldhihowareyou". toString()将返回“ helloworldhihowareyou”。 If you want the words separated in the result string, append a space char (or other separator?) to each element of arrayStr before adding it to the StringBuilder object. 如果要在结果字符串中将单词分隔开,请在将arrayStr的每个元素添加到StringBuilder对象之前,将一个空格字符(或其他分隔符?)添加到该数组中。

String singlestr="hello|world|how|are|you";
String[] arraystr = singlestr.split("|");
StringBuilder builder = new StringBuilder ();
String newString;

for (String s: arraystr) {
    builder.append(s.concat(" "));  // Add with separator
}

builder.insert(10,"hi");
newString = builder.toString();

Edit: consolidated code segments and removed redundant talking. 编辑:合并代码段并删除多余的谈话。 :) :)

My first suggestion would be to store your data in a LinkedList before you insert the element. 我的第一个建议是在插入元素之前将数据存储在LinkedList中。 That class has an add(index, value) type method that does exactly what you want. 该类具有一个add(index,value)类型的方法,可以完全满足您的需要。 So for example, 例如

LinkedList<String> list = new LinkedList(arraystr);
list.add(2,"hi");

If you must have an array at the end,then you could use a linked list to hold your data, then use the toArray() method to convert it back (to a new larger array) 如果必须在末尾有一个数组,则可以使用链表保存数据,然后使用toArray()方法将其转换回(新的更大数组)

String[] newArray = list.toArray();

If you aren't allowed to use a LinkedList to even hold your data, I see no alternative than moving all the later values down one notch in some kind of loop, and then adding your value in the space created. 如果不允许您使用LinkedList甚至保存数据,那么除了在某种循环中将所有以后的值向下移动一个凹口,然后在创建的空间中添加值,我认为别无选择。 But as someone else pointed out, you can't increase the size of an array. 但是正如其他人指出的那样,您不能增加数组的大小。 So unless your array has additional space (doesn't in your case) you will need to create a new larger array anyway. 因此,除非您的阵列有额外的空间(在您的情况下没有),否则您仍然需要创建一个更大的新数组。 In which case you are really better off using one of the List implementations. 在这种情况下,使用List实现之一确实更好。

String arrays cannot increase their size. 字符串数组不能增加其大小。 If you wanted to add to it you would need to instantiate a completely new array and then copy the values from your initial array to the new string array. 如果要添加到它,则需要实例化一个全新的数组,然后将值从初始数组复制到新的字符串数组。

Example: 例:

In this example we are using a for-loop to loop through all of the indexes and assigning them to the new array, however when we get to the desired index we are assigning a new value thus "shifting" the other values in the new array. 在此示例中,我们使用for循环遍历所有索引并将它们分配给新数组,但是当我们到达所需索引时,我们将分配一个新值,从而“移位”新数组中的其他值。

String[] first = {"hello", "world", "how", "are", "you"};
String[] second = new String[5];

for(int i = 0; i < first.length; i++){
    if(i != 2){
         second[i] = first[i];
    }else{
         second[2] = "hi";
    }
}

for(String s: second){
        System.out.println(s);
}

Super ugly no? 超级丑不?

I would recommend using an ArrayList or List instead. 我建议改用ArrayList或List。 Arraylists have the ability to have their length increased without needing to do anything special to the initial array. 数组列表可以增加其长度,而无需对初始数组进行任何特殊处理。 You can simply say add(index, value). 您可以简单地说add(index,value)。

Example: 例:

ArrayList<String> values = new ArrayList<>();
values.add("hello");
values.add("world");
values.add("how");
values.add("are");
values.add("you");
values.add(2,"Hi"); //adding to index 2!

Now if for some reason you do need a regular old array, it is super easy to just convert your arraylist back to an array. 现在,如果由于某种原因您确实需要一个常规的旧数组,那么只需将arraylist转换回一个数组就非常容易。

String[] newVal = new String[5];
values.toArray(newVal);

You need to copy over the elements to a new, slightly larger array. 您需要将元素复制到稍大的新数组中。 System.arraycopy() is probably the most efficient method: System.arraycopy()可能是最有效的方法:

String singlestr="hello|world|how|are|you";
String[] arraystr = singlestr.split("\\|"); // Note: pipe needs to be regex-escaped
String[] newarray = new String[arraystr.length + 1];
System.arraycopy(arraystr, 0, newarray, 0, 2);
newarray[2] = "hi";
System.arraycopy(arraystr, 2, newarray, 3, arraystr.length - 2);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM