-2

I have a string which is (30) can someone please help me to split it as below

  1. (
  2. 32
  3. )

My concern is there is no spaces between the brackets and number. After splitting I wants to store each and every character to separate variable and I want to convert "32" in to integer value to use it

Nisal Edu
  • 7,237
  • 4
  • 28
  • 34

4 Answers4

1

One option uses lookarounds to determine where the split should take place. Assuming that you want a split to happen at the boundary between a word a non word character, lookarounds would work because they assert but do not consume, leaving all the input to appear in the result.

String input = "(32)";
String[] parts = input.split("(?<=[^A-Za-z0-9])(?=[A-Za-z0-9])|(?<=[A-Za-z0-9])(?=[^A-Za-z0-9])");
for (String part : parts) {
    System.out.println(part);
}

(
32
)

Demo

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • I didn't get u please help me in detail – Narendra Chetan Jan 18 '18 at 06:40
  • @NarendraChetan Your question has been closed because it is unclear what you are asking. Edit your question and tell us the logic by which your input gets split the way that it does. My answer is correct, under certain assumptions. – Tim Biegeleisen Jan 18 '18 at 06:41
1

Regex pattern "\\b" is used match word separated by delimiter.

public class Main {
    public static void main( String[] str ) {

        String[] split = splitStr( "(32)" );
        for ( String s : split ) {
            System.out.println(s);
        }
    }

    public static String[] splitStr( String str ) {
        String regex = "\\b";
        return str.split(regex);
    }
}
0

Try as follows use toCharArray()

String str = "(32)";

char[] chars = str.toCharArray();

System.out.println(chars[0]);
System.out.println(chars[1]);
System.out.println(chars[2]);
System.out.println(chars[3]);
Nisal Edu
  • 7,237
  • 4
  • 28
  • 34
0

It seems you want to keep the split characters as well, so using String.split() 'normally' will not do. For that, I would go with lookarounds already proposed, but with a simpler pattern:

import java.util.Arrays;

public class Splitter {
  public static void main(String args[]) {
    String str = "(30)";
    String[] results = str.split("(?<=[()])|(?=[()])");
    System.out.println(Arrays.toString(results)); // [(, 30, )]
  }
}

This pattern will use characters '(' and ')' as tokens to use for splitting, but keeps the tokens as well.

If you're interested, there's more discussion on using lookarounds in this thread.

eis
  • 51,991
  • 13
  • 150
  • 199