Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,239 questions

56,142 answers

573 users

How to split a string into words in Java

2 Answers

0 votes
import java.util.ArrayList;
import java.util.List;

public class SplitString {

    public static List<String> SplitString(String s, String delims) {
        String[] parts = s.split(delims);

        List<String> tokens = new ArrayList<>();
        for (String p : parts) {
            if (!p.isEmpty()) {
                tokens.add(p);
            }
        }

        return tokens;
    }

    public static void main(String[] args) {
        String s = "-c, c++.. c#:: -java ,!php!...python     go";

        // multiple delimiters: space, comma, dot, colon, dash, plus, exclamation
        String delims = "[ ,.:\\-!]+";

        List<String> tokens = SplitString(s, delims);

        for (String t : tokens) {
            System.out.println(t);
        }
    }
}


/*
run:

c
c++
c#
java
php
python
go

*/

 



answered Feb 4, 2017 by avibootz
edited Aug 29 by avibootz
0 votes
import java.util.Set;
import java.util.List;
import java.util.Arrays;
import java.util.HashSet;

public class SplitStringProgram {

    public static List<String> splitString(String s, String delims) {
        Set<Character> delimSet = new HashSet<>();
        for (char ch : delims.toCharArray()) {
            delimSet.add(ch);
        }

        StringBuilder normalized = new StringBuilder();
        for (char ch : s.toCharArray()) {
            normalized.append(delimSet.contains(ch) ? ' ' : ch);
        }

        String[] parts = normalized.toString().split("\\s+");

        return Arrays.asList(parts);
    }

    public static void main(String[] args) {
        String s = "-c, c++.. c#:: -java! ,php...python:      go!";
        String delims = " ,.:\\-!";

        List<String> tokens = splitString(s, delims);

        for (String t : tokens) {
            System.out.println(t);
        }
    }
}


/*
run:

c
c++
c#
java
php
python
go

*/

 



answered Aug 29 by avibootz
...