简体   繁体   中英

Java: Finding part of a string in a String Array and making a new array

I have a list in a array, each entry either contains o: or g: in front of a word, like o:word or g:word. I want 2 functions, one to make an array with just the g:'s and one to make an array with just the o:'s

I also want the g:'s and o:'s to be pruned out of the result. I'm not sure how to do this without causing array out of bounds errors and such, so I was wondering if someone could give me an example.

Smells like homework.

String[] array = ...

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

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

for (String word : array) {  
    if (word != null)) {  
        if (word.startsWith("g:"))   
            gList.add(word.subString(2));  
        else if (word.startsWith("o:")
            oList.add(word.subString(2));  
    } 
}

One way is to use ArrayList s to create the new lists. If you need to have primitive arrays after you've got the two new lists, just use toArray() on them.

You would be better off working with ArrayLists (than arrays), because you don't know in advance what size the result will be. But you can make two passes, one to count the rows with the prefix of interest, and a second to populate the new array.

int n = 0;
for (int i = 0; i < array.size; i++)
  if (array[i].startsWith(prefix))
    n++;

String[] result = new String[n];
int j = 0;

for (int i = 0; i < array.size; i++)
  if (array[i].startsWith(prefix))
    result[j++] = array[i].substring(prefix.length());

Untried, but I think that ought to do the job.

Assuming that you can mess up the original array, and that you don't need to preserve the order, this should be quite fast:

String[] array = {"o:1","o:2","g:10","o:3","g:20","o:4","g:30","g:40","o:5"};
int low = 0;
int high = array.length - 1;
while(low <= high) {
    if(array[low].startsWith("g:")) {
        array[low] = array[low].substring(2);
        low ++;
    } else if (array[high].startsWith("o:")) {
        array[high] = array[high].substring(2);
        high --;
    } else {
        String temp = array[low].substring(2);
        array[low] = array[high].substring(2);
        array[high] = temp;
        low++;
        high--;
    }
}
String[] gs = new String[low];
System.arraycopy(array, 0, gs, 0, low);
String[] os = new String[array.length - low];
System.arraycopy(array, low, os, 0, array.length - low);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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