Copy data from a longer array to a shorter array

72 Views Asked by At

I would like to copy only certain data from an old array of chars to a new array of chars. This is what I have thus far:

char[] charsInString = s.toCharArray();

int length = 0;
for (int i = 0; i < charsInString.length; i++) {
    if (!(charsInString[i] < 65 || charsInString[i] > 122))
        length++;
}

char[] newCharList = new char[length];
for (int i = 0; i < charsInString.length; i++) {
    // not sure what to do here?
}

I only want chars in the new array that correspond with letters in the alphabet (a, b, c, etc.), essentially copying the old char array without the chars that correspond to numbers, punctuation, spaces, etc. Is there any way to do this? I have tried using both for loops and while loops, but it is just not working. Suggestions?

2

There are 2 best solutions below

0
Zachary On

Strip all non-alphabetic characters from the Original string before converting to a character array.

String stripped = s.replaceAll("[^a-z]", "");
char[] charsInString = stripped.toCharArray();

This solution is not the most efficient, however, unless your input String is very long this should be negligible.

0
mohanish On

Try this code

    String str = " @#$%@##$%$& @#$%#$   alph #$%a#$%# be&*%#@ts";
    char[] charsInString = str.toCharArray();

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < charsInString.length; i++) {
        if ((charsInString[i] > 65 && charsInString[i] < 122))
            sb.append(charsInString[i]);
    }

    char[] newCharList = sb.toString().toCharArray();

    System.out.println(newCharList);

Output:

alphabets