1

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?

Aniket Sahrawat
  • 12,410
  • 3
  • 41
  • 67
  • 2
    `int i = 0; for (char c : charsIntString) if (Character.isAlphabetic(c)) newCharList[i++] = c;` – shmosel Jan 31 '18 at 02:46

2 Answers2

3

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.

Zachary
  • 1,693
  • 1
  • 9
  • 13
0

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
mohanish
  • 41
  • 1