I'm currently working on a project for a class to create a TextLine class that represents the a line of text that must be represented as an array of characters.
For one of the methods, I am supposed to take in a string as an argument of a parameter and then append that string to my already created char array.
I was trying to search online for how I could do this, or even an example of the String or StringBuffer class that showed the implementation, but due to my novice skills at Google, I couldn't really find anything useful.
What I 'm thinking is that I first have to convert the string to the array, and then somehow using one of the array methods to add each char individually to the char array.
This is what I have:
public void append(String fragment){
char[] temp = fragment.toCharArray();
}
I'm not quite sure what array method could b开发者_如何学编程e used, if there even is one. Could someone please help me?
Normally you would use a StringBuilder
as the internal storage for your class but i assume that you need the basic details of how to do this.
The basic process is like this:
- allocate a new array with the size of old array + size of the new data
- copy the old data into the new array
- copy the new data at the end of the new array
- set this as the actual data
Here is the code (this assumes that the data
member is declared like this: char[] data = new char[0]
:
public void append(String fragment) {
char[] fragmentChars = fragment.toCharArray();
char[] newData = new char[data.length + fragmentChars.length];
System.arraycopy(data, 0, newData, 0, data.length);
System.arraycopy(fragmentChars, 0, newData, data.length, fragmentChars.length);
data = newData;
}
Let's say your original char[]
array is called arr
. Then you can do:
public void append(String fragment){
arr = (new String(arr)+fragment).toCharArray();
}
This converts your char[]
array into a String
so you can simply concatenate that to fragment
using the +
operator. Then you simply convert the new String
back to a char[]
array using toCharArray()
.
You can use the System.arraycopy method to copy the contents of one array into another array. I'll leave it as an exercise to figure out the details.
As an alternative, you can try a slightly more straightforward method:
public class Test{
char[] arr;
public static void main(String[] args){
Test t = new Test();
t.arr = "hi ".toCharArray();
t.append(" and bye");
System.out.print(new String(t.arr));
}
public void append(String myString){
char[] toAppend = myString.toCharArray();
char[] newArr = new char[toAppend.length+arr.length];
for(int i = 0; i < arr.length; i++)
newArr[i] = arr[i];
for(int i = 0; i < toAppend.length-1; i++)
newArr[i+arr.length] = toAppend[i];
arr = newArr;
}
}
精彩评论