javaarraysstringjxl

java split a string and put into an array position


So i am using string.split because i need to take certain parts of a string and then print the first part. The part size may vary so I can't use substring or a math formula. I am attempting to store everything I need in the string array to then selectively print what I need based on the position, this much I can control. However, I am not sure what to do because I know when I do a split, it takes the two parts and stores them in the array. However, there is one case where I need that value in the array untouched. I'm afraid if I do

format[0] = rename

That it will overwrite that value and mess up the entire array. My question is how do I assign a position to this value when I don't know what the position of the others will be? Do I need to preemptively assign it a value or give it the last possible value in the array? I have attached a segment of the code that deals with my question. The only thing I can add is that this is in a bigger loop and rename's value changes every iteration. Don't pay to much attention to the comments, those are more of reminders for me as to what to do rather than what the code is suppose to do. Any pointers, tips, help is greatly appreciated.

String format[];
rename = workbook.getSheet(sheet).getCell(column,row).getContents();
for(int i = 0; i < rename.length(); i++) {
    //may need to add[i] so it has somewhere to go and store
    if(rename.charAt(i) == '/') {                                
        format = rename.split("/");
    }
    else if(rename.charAt(i) == '.') {
        if(rename.charAt(0) == 0) {
           //just put that value in the array
           format = rename;
        } else {
            //round it to the tenths place and then put it into the array
            format = rename.split("\\.");
        }
    } else if(rename.charAt(i) == '%') {
        //space between number and percentage
        format = rename.split(" ");
    }
}

Solution

  • Whenever you assign a variable it gets overwritten

    format[0] = rename
    

    Will overwrite the first index of this array of Strings.

    In your example, the 'format' array is being overwritten with each iteration of the for loop. After the loop has been completed 'format' will contain only the values for the most recent split.

    I would suggest looking into using an ArrayList, they are much easier to manage than a traditional array and you can simply just iterate through the split values and append them at the end.