0

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? is there any functions?

Expected output after inserting a new string to index 2:

arraystr[0]=hello
arraystr[1]=world
arraystr[2]=hi
arraystr[3]=how
arraystr[4]=are
arraystr[5]=you
1
  • Array has limitations like you can assign only single type data, length should be declare, you can't change length runtime, so better is use collections like list or arraylist for this it will resolve your issue and it has advantage over simple array like this Commented Jul 18, 2016 at 4:38

5 Answers 5

2

Try using a StringBuilder. Use the append() method to insert the elements from arrayStr, then use insert() to insert new text at the desired location. The toString() method will return the finished string.

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(). Also, your example splits the initial string into separate words with no embedded separators. toString() would return "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.

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();
Sign up to request clarification or add additional context in comments.

Comments

1

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.

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. 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).

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.

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

2 Comments

Ok this seems helpful. Thank you for your effort. I will check it and accept the answer after that. Thank you very much @basic :)
@jdoe No worries that is what SO is here for :)
0

You need to copy over the elements to a new, slightly larger array. System.arraycopy() is probably the most efficient method:

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);

Comments

0

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. That class has an add(index, value) type method that does exactly what you want. 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)

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. 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.

Comments

0

I know it's old, but I found this minutes ago, and what I do is:

for (int i=textrray.size(); i>2; i--) {
    textarray.set(i-1,textarray.get(i-2));
}
textarray.set(1, textarray.get(0));
textarray.set(0, "new content at array position 1"); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.