Wednesday 4 May 2022

How to split a string by dot (.) in Java?

Approach 1: Using StringTokenizer.

Example

StringTokenizer stringTokenizer = new StringTokenizer(str, ".");
while (stringTokenizer.hasMoreTokens()) {
            System.out.println(stringTokenizer.nextToken());
}

Above snippet construct a StringTokenizer object for the string str using the delimiter ‘.’.

 

SplitByDotUsingTokenizer.java

package com.sample.app.strings;

import java.util.StringTokenizer;

public class SplitByDotUsingTokenizer {

	public static void main(String args[]) {
		String str = "hello.world.how.are.you";

		StringTokenizer stringTokenizer = new StringTokenizer(str, ".");

		while (stringTokenizer.hasMoreTokens()) {
			System.out.println(stringTokenizer.nextToken());
		}
	}

}

 

Approach 2: Using Regular Expressions

Since ‘.’ is a regular expression pre defined character class, we need to explicitly escape it using a backslash while splitting by dot.

 

String[] tokens1 = str.split("\\.");

 

you can even use the [.] form to split the String by dot.

 

String[] tokens2 = str.split("[.]");

 

SplitByDotUsingRegularExpressions.java

package com.sample.app.strings;

public class SplitByDotUsingRegularExpressions {

	public static void main(String args[]) {
		String str = "hello.world.how.are.you";

		String[] tokens1 = str.split("\\.");
		String[] tokens2 = str.split("[.]");

		for (String token : tokens1) {
			System.out.println(token);
		}

		System.out.println("\n\n");
		
		for (String token : tokens2) {
			System.out.println(token);
		}
	}

}

 

Output

hello
world
how
are
you



hello
world
how
are
you

 


Approach 3: With the help of custom logic

 

SplitByDot.java

package com.sample.app.strings;

import java.util.ArrayList;
import java.util.List;

public class SplitByDot {

	public static List<String> splitBy(String str, char separator) {
		char[] chars = str.toCharArray();

		StringBuilder builder = new StringBuilder();

		List<String> tokens = new ArrayList<>();

		for (char ch : chars) {

			if (ch == separator) {
				tokens.add(builder.toString());
				builder = new StringBuilder();
				continue;
			}

			builder.append(ch);

		}

		if (!builder.toString().isEmpty())
			tokens.add(builder.toString());

		return tokens;
	}

	public static void main(String[] args) {
		String str = "hello.world.how.are.you";

		List<String> tokens = splitBy(str, '.');

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

	}

}

Output

hello
world
how
are
you




 

Previous                                                 Next                                                 Home

No comments:

Post a Comment