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?

1
  • 2
    int i = 0; for (char c : charsIntString) if (Character.isAlphabetic(c)) newCharList[i++] = c; Commented Jan 31, 2018 at 2:46

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.