Split a string into different parts with dynamic length [duplicate] - java

This question already has answers here:
How to split a String by space
(17 answers)
Closed 1 year ago.
I have a problem in my Java code:
I want to split a string in parts an undefined amound of parts with different length. I want to split it whenever a space appears in the string.

You can split string easily like this:
class HelloWorld {
public static void main(String[] args) {
String str = "Hey there welcome to java!";
String[] splited = str.trim().split("\\s+");
for (String word : splited)
{
System.out.println(word);
}
}
}
Output:
Hey
there
welcome
to
java!

Related

This program is not showing correct output [duplicate]

This question already has answers here:
Split string with dot as delimiter
(13 answers)
Closed last month.
Code:
public class StringBuffer_Filtering_data
{
public static void main(String[] args)
{
String [] records={
"1001.ajay.manager.account.45000.male.38",
"1002.aiswrya.clerk.account.25000.female.30",
"1003.varun.manager.sales.50000.male.35",
"1004.amit.manager.account.47000.male.40",
"1005.kareena.executive.sales.15000.female.24",
"1006.deepak.clerk.sales.23000.male.30",
"1007.sunil.accountant.sales.13000.male.29",
"1008.satvik.director.purchase.80000.male.45"
};
StringBuffer sb=new StringBuffer(255);
for(String record:records)
{
String[] fields=record.split(".");
if(fields[2].equals("manager"))
{
System.out.println(record);
}
}
}
}
Expected output:
1001,ajay,manager,account,45000,male,38
1003,varun,manager,sales,50000,male,35
1004,amit,manager,account,47000,male,40
split's argument is a regular expression (regex), not a plain old string. In the context of a regex, . is a special character while means "any character". If you want to split the string by the literal ., you'll need to escape it:
String[] fields=record.split("\\.");
// Here ----------------------^^

How do I split a string by whole strings? [duplicate]

This question already has answers here:
How do I split a string in Java?
(39 answers)
Closed 3 years ago.
So, I am trying to split a string but I don't just want to split it by single character strings, but rather by entire strings.
So if my String is ["hello buddy my name is buddy"], my delimiter would be "buddy".
I want it to split into: ["hello", "my name is"].
I hope i'm not over complicating it.
public static void main(String[ ] args) {
String test = "hello buddy my name is buddy";
String[] res = test.split("buddy");
for (String s: res) {
System.out.println(s);
}
}
Seems to do what you want, no?

Split a word by a char in Java [duplicate]

This question already has answers here:
How to split a string, but also keep the delimiters?
(24 answers)
How do I split a string in Java?
(39 answers)
Closed 3 years ago.
Consider the following example. I would like to divide the String into two parts by the char 'T'
// input
String toDivideStr = "RaT15544";
// output
first= "RaT";
second = "15544";
I've tried this:
String[] first = toDivideStr.split("T",0);
Output:
first = "Ra"
second = "15544"
How do I achieve this?
What you need to to, is locate the last "T", then split:
StringToD.substring(StringToD.lastIndexOf("T") + 1)
You could use a positive lookahead to assert a digit and a positive lookbehind to assert RaT.
(?<=RaT)(?=\\d)
For example:
String str = "RaT15544";
for (String element : str.split("(?<=RaT)(?=\\d)"))
System.out.println(element);
Regex demo | Java demo
You can use positive look-ahead with split limit parameter for this. (?=\\d)
With only T in the split method parameter, what happens is the regex engine consumes this T. Hence the two string split that occurs doesn't have T. To avoid consuming the characters, we can use non-consumeing look-ahead.
(?=\\d) - This will match the first number that is encountered but it will not consume this number
public static void main(String[] args) {
String s = "RaT15544";
String[] ss = s.split("(?=\\d)", 2);
System.out.println(ss[0] + " " + ss[1]);
}
The below regex can be used to split the alphabets and numbers separately.
String StringToD = "RaT15544";
String[] parts = StringToD.split("(?<=\\d)(?=\\D)|(?<=\\D)(?=\\d)");
System.out.println(parts[0]);
System.out.println(parts[1]);

Can't split text that contain "|" in String [duplicate]

This question already has answers here:
How to split a string on | (pipe) in Java [duplicate]
(3 answers)
Closed 7 years ago.
I'm wondering why I cannot split a text that contain the | as a separator in String. The splitting works fine when I use commas or the like..
Here is an SSCE
package tests;
public class Tests {
public static void main(String[] args) {
String text1="one|two|three|four|five";
String text2="one,two,three,four,five";
String [] splittedText1 = text1.split("|");
String [] splittedText2 = text2.split(",");
for(String elem : splittedText1) System.out.println("text1="+elem);
for(String elem : splittedText2) System.out.println("text2="+elem);
}
}
Any ideas why it doesn't work with "|" ??
Since split(String regex) takes a regex and | is a meta character, you need to escape it.
String[] splittedText1 = splittedText1.split("\\|");
Or you can simply use Pattern class
A compiled representation of a regular expression.
String[] splittedText1 = splittedText1.split(Pattern.quote("|"));
Because the split pattern is actually a regex. You need to escape |, since it has a special meaning in the context of a regular expression (it marks an alternative):
String [] splittedText1 = text1.split("\\|");

Split a string in Java based on a separator unless separator is escaped with String.split [duplicate]

This question already has an answer here:
Java regex : matching a char except when preceded by another char
(1 answer)
Closed 8 years ago.
I got a string in java that I would like to split in parts on following criteria:
the '#' char is a separator
if '#' is escaped via backslash then is should not be considered a separator
i.e.
"abc#xyz#kml\#ijk"
should be split into
"abc", "xyz", "kml\#ijk"
I can do it easily with StringTokenizer and add some logic for the escape char but I would like to get it via one-liner String.split call with the correct regex. So far my "best" attempt is following:
public static void main(String[] args) {
String toSplit = "abc#xyz#kml\\#ijk";
String[] arr = toSplit.split("[^\\\\]#");
System.out.println(Arrays.toString(arr));
}
and the result is:
[ab, xy, kml#ijk]
The last letter of the first two parts is cut out.
Any idea how to avoid that?
Have you looked into lookbehinds?
public static void main(String[] args) {
String toSplit = "abc#xyz#kml\\#ijk";
String[] arr = toSplit.split("(?<!\\\\)#");
System.out.println(Arrays.toString(arr));
}

Categories