Home > database >  How can I take out some parts of the String?
How can I take out some parts of the String?

Time:03-26

I have a String value like this.

"Apple:1#Banana:2#Cake:3#Dog:4#Elephant:5"

a word : a number # a word : a number ...

and I want to separate the Strings into:

Apple

1

Banana

2

Cake

3

Dog

4

Elephant

5

...

However, I do not know how long the String is. Is there any way I can split each content connected with ":" and "#"?

CodePudding user response:

Split on : or #:

String[] parts = str.split("[:#]");

CodePudding user response:

You can replace all : symbol to # and split the string by #.

String str = "Apple:1#Banana:2#Cake:3#Dog:4#Elephant:5#";
       String strrep = str.replaceAll(":","#");
        String splitted[] = strrep.split("#");
        for (String i : splitted){
           System.out.println(i);
        }

CodePudding user response:

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter your input: ");

        String input = scanner.nextLine();
        Arrays.stream(input.split("[:#]")).forEach(System.out::println);
    }
}

This is the code that gets input for example Apple:1#Banana:2#Cake:3#Dog:4#Elephant:5 and it will split the input by # and : and print them line by line.

The result shown on the console will be like

Enter your input: 
Apple:1#Banana:2#Cake:3#Dog:4#Elephant:5
Apple
1
Banana
2
Cake
3
Dog
4
Elephant
5

Or you can do with a simpler way without streams

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter your input: ");

        String input = scanner.nextLine();
        for (int i = 0; i < input.length();) {
            int nextHashIdx = input.indexOf("#", i);
            if (nextHashIdx == -1) nextHashIdx = input.length();

            String strWithColon = input.substring(i, nextHashIdx);
            String[] strs = strWithColon.split(":");
            System.out.println(strs[0]);
            System.out.println(strs[1]);

            i = nextHashIdx   1;
        }
    }
}
  • Related