0

I'm making a program that should ignore ( and ) in words (without the use of RegExp), and through the method I created, I want my variable x to memorize the new String. How can I access subSequence in such way or circumvent my issue through another method that doesn't include the use of RegExp?

public int removeParentheses(char[] str) {
    // To keep track of '(' and ')' characters count 
    int count = 0;

    for (int i = 0; i < str.length; i++)
        if (str[i] != '(' && str[i] != ')')
            str[count++] = str[i];

    return count;
}

public String foo(String input) {

    for (String index : input.split(" ")) {
        char[] charArray = index.toCharArray();
        int k = removeParentheses(charArray);
        String x = String.valueOf(charArray).subSequence(0, k); // that's what i want to do. it doesn't work.
        System.out.println(String.valueOf(charArray).subSequence(0, k)); // this is the only way i can make it work, but it doesn't suffice my needs
    }
}

The current output is

 error: incompatible types: CharSequence cannot be converted to String
                        String x = String.valueOf(charArray).subSequence(0, k);
                                                                        ^
1 error

I expect the output of boo) to be boo in my x variable, not just on-screen through the System.out.println method.

Kaan
  • 5,434
  • 3
  • 19
  • 41
soulblast
  • 3
  • 1
  • You're using `CharSequence#subSequence` which returns a `CharSequence`. Use `String#substring` instead as it returns `String`. – Slaw Oct 21 '19 at 03:17

1 Answers1

0

You said this is "what i want to do. it doesn't work.":

String x = String.valueOf(charArray).subSequence(0, k);

The return value of subSequence() is a CharSequence which is not a String. It makes sense that it wouldn't work.

Since you are starting from an array of characters – char [] – you could use Arrays.copyOfRange() to create a new array of some smaller subset of charArray, like this:

char[] copy = Arrays.copyOfRange(charArray, 0, k);

From there, you could construct a new Stringnew String(copy) – or possibly just use that new character array directly.

Kaan
  • 5,434
  • 3
  • 19
  • 41