split string only on first instance - java - java

I want to split a string by '=' charecter. But I want it to split on first instance only. How can I do that ? Here is a JavaScript example for '_' char but it doesn't work for me
split string only on first instance of specified character
Example :
apple=fruit table price=5
When I try String.split('='); it gives
[apple],[fruit table price],[5]
But I need
[apple],[fruit table price=5]
Thanks

string.split("=", limit=2);
As String.split(java.lang.String regex, int limit) explains:
The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string. The substrings in the array are in the order in which they occur in this string. If the expression does not match any part of the input then the resulting array has just one element, namely this string.
The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter.
The string boo:and:foo, for example, yields the following results with these parameters:
Regex Limit Result
: 2 { "boo", "and:foo" }
: 5 { "boo", "and", "foo" }
: -2 { "boo", "and", "foo" }
o 5 { "b", "", ":and:f", "", "" }
o -2 { "b", "", ":and:f", "", "" }
o 0 { "b", "", ":and:f" }

Yes you can, just pass the integer param to the split method
String stSplit = "apple=fruit table price=5"
stSplit.split("=", 2);
Here is a java doc reference : String#split(java.lang.String, int)

As many other answers suggest the limit approach, This can be another way
You can use the indexOf method on String which will returns the first Occurance of the given character, Using that index you can get the desired output
String target = "apple=fruit table price=5" ;
int x= target.indexOf("=");
System.out.println(target.substring(x+1));

String string = "This is test string on web";
String splitData[] = string.split("\\s", 2);
Result ::
splitData[0] => This
splitData[1] => is test string
String string = "This is test string on web";
String splitData[] = string.split("\\s", 3);
Result ::
splitData[0] => This
splitData[1] => is
splitData[1] => test string on web
By default split method create n number's of arrays on the basis of given regex. But if you want to restrict number of arrays to create after a split than pass second argument as an integer argument.

This works:
public class Split
{
public static void main(String...args)
{
String a = "%abcdef&Ghijk%xyz";
String b[] = a.split("%", 2);
System.out.println("Value = "+b[1]);
}
}

String[] func(String apple){
String[] tmp = new String[2];
for(int i=0;i<apple.length;i++){
if(apple.charAt(i)=='='){
tmp[0]=apple.substring(0,i);
tmp[1]=apple.substring(i+1,apple.length);
break;
}
}
return tmp;
}
//returns string_ARRAY_!
i like writing own methods :)

Related

Tricky Java problem to split and manipulate String

I need to create a function in Java translate_string(),
which is doing "translation" of the string letter by letter.
Function takes String as arg, and returns array of String[]:
public static String[] translate_string(String string)
Given existing function translate_letter(),
which takes String as arg and returns array of String[]
public static String[] translate_letter(String letter)
and it translating each letter, I need to sequentially translate
the whole string letter by letter into combination of output strings.
Complexity is, that one character could be translated to multiple
sets of characters, it is not one-to-one relationship between
input string and output string, it is - one-to-many relationship,
where one letter as input could produce multiple combinations
(i.e. arrays) as output.
N.B.: Term translation has nothing to do with actual translation from
one language to another, it is just substitution of one character
to set of other characters.
Below is exact code id simplified version of function
translate_letter() (no modification is required):
//------------------------------------------------------------
// translate letters - return array of diff combinations
public static String[] translate_letter(String s) {
ArrayList<String> o = new ArrayList<>(1);
if ( s.equals("a") ) { // if a
o.add("a1");
} else {
if ( s.equals("b") ) { // if b
o.add("b1"); o.add("b2");
} else {
if ( s.equals("c") ) { // if c
o.add("c1"); o.add("c2"); o.add("c3");
} else {
if ( s.equals("d") ) { // if d
o.add("d1"); o.add("d2"); o.add("d3"); o.add("d4");
} else {
o.add(s); // s = def add (if nothing above matches)
} // end if d
} // end if c
} // end if b
} // end if a
//Convert ArrayList o to string array[]
String[] array = o.toArray(new String[o.size()]);
return array;
} // end translate_letter()
//------------------------------------------------------------
So, how to translate the string?
Let's have a look at simple version of translate - when
translate_letter() return just string.
So, letter "a" will be translated to "a1", letter "b"
will be translated to "b1", "c" - to "c1".
Input string "a" will be translated as "a1", simple.
Input string "ab" will be translated as "a1b1", simple.
Input string "abc" will be translated as "a1b1c1", simple.
I don't need to create this simple version - it is nothing to do here,
just split the input string and translate each letter by letter.
What I want to write (and I cannot do this) - is complicated version of translate_string(),
when function translate_letter() returns multiple combinations,
i.e. - array of output combinations.
For example (according to the code of translate_letter() above,
letter "a" will be translated to "a1", simple.
But letter "b" will be translated by translate_letter() to 2 combinations:
"b1" and "b2",
and output is String[] array = {"b1", "b2" }
So, string "a" will be translated by translate_string() as array of
just 1 element R[] = { "a1" }
String "ab" will be translated as array of 2 elements
R[] = { "a1b1", "a1b2" }
String "abc" will be translated as:
R[] = { "a1b1c1", "a1b1c2", "a1b1c3", "a1b2c1", "a1b2c2", "a1b2c3" }
String "db" will be translated as:
R[] = { "d1b1", "d2b1", "d3b1", "d4b1", "d1b2", "d2b2", "d3b2", "d4b2" }
This task is more complicated, than it seems initially just by
look at it. I have tried and failed with 2 approaches - simple Arrays[]
and Array[] of ArrayList - cannot loop through two array (with different
indexes) at once and need some external help or ideas - how to accomplish this.
You need a recursive translateString method (according to Java naming conventions named in camel case without any underscore in the name). The algorithm is:
If string is the empty string, return an array of one element, the empty string.
From translateLetter() obtain all possible translations of the first letter.
From a recursive call to translateString() obtain all possible translations of the remainder of the string after the first letter. Or for the shortcut: just call translateString() passing the part of the string that comes after the first character as argument.
In two nested loops concatenate each possible translation of the first letter with each possible translation of the remainder of the string. One of the loops will iterate over the possible translations of the first letter obtained from 2. above. The other loop over the possible translations of the remainder of the string obtained from 3. Add the concatenated strings to an ArrayList<String>.
Convert the list to an array and return it.
This is one of the rare occasions I'll answer homework, though Ole V.V. is right.
When we do the homework, the learning effect is relative, and it is not honest with respect to those wo struggled.
public static String[] translate_string(String s) {
Set<String> translations = new HashSet<>();
if (!s.isEmpty()) {
s.codePoints(cp -> {
String letter = new String(new int[] {cp}, 0, 1);
String[] more = translate_letter(letter);
if (more.length == 0) {
} else if (more.length == 1) {
translations.add(more[0]);
} else {
Set<String> prior_translations = new HashSet<>(translations);
translations.clear();
for (String prior: prior_translations) {
for (String letter: letter_translations) {
translations.add(prior + letter);
}
}
}
});
}
return translations.toArray(new String[0]);
}
The trick is: when having N translations and getting for a next letter L letter translations, the result is N×L translations.
The answer of Ole V.V. explains things better.

How to divide a String into identical repeating parts

Given a String, I want to divide it up into substrings that are all identical. For example:
"abcabcabcabc" -> ["abc", "abc", "abc", "abc"]
"aaaaaa" -> ["a", "a", "a", "a", "a", "a"]
"abc" -> ["abc"]
My problem is figuring out the logic of finding where to break the characters. My approach initial attempt is:
public static void FindPattern(String s) {
int no_of_characters = 256;
int[] count = new int[no_of_characters];
Arrays.fill(count, 0);
for (int i= 0; i < s.length();i++){
count[s.charAt(i)]++;
}
}
public static void main(String[] args) {
String s = "abcabcabd";
FindPattern(s);
}
but I have no idea of where to go from there.
You can use regex to find the smallest substring that when repeated is the same as the whole string:
String part = str.replaceAll("^(.+?)\\1*$", "$1");
Breaking down the regex:
^ means "start of input"
(.*?) means "capture (as group 1) the smallest amount of input that will result in a match"
\1 is a back reference to group 1, meaning "another copy of what was captured in group 1"
* zero or more of the the back reference
$1 the replacement is what was captured in group 1
Because zero further copies are allowed to complete the match, when there is no repeating group, the whole string is returned, which is correct behaviour.
Once you have this string, you don't actually need to "divide" the string up, you just need n copies of it. However as a convenience you can split the sting equal parts by splitting on the length of the result of the above:
String[] parts = str.split("(?<=\\G.{" + str.replaceAll("^(.*?)\\1*$", "$1").length() + "})");
More simply, the split regex is (?<=\G.{n}), which means "there are n characters between the end of the previous match and the current position".

String split function in Java

I have a String and I want to split it by ","
If suppose I have a String like,
String test = "aa,bb,cc";
now I can split it by,
String[] spl = test.split(",");
And the spl.length is 3
If suppose my String is
String test = ",,,";
Here the splitted String length is 0. But my expected answer is 3.
My test String is dynamaic value and it may varies like, Now think I have a String like
String test = ",aa,dd,,,,,ff,gg"
Now the splited array length is 4. But I expected answer is 9
And I need to split by "," and I need the aa position at spl[1] and dd position as spl[2] and ff position as spl[7]
Can someone give the suggestion about to solve this issue..
Use split() with -1 as limit
public static void main(String[] args) {
String test = ",,,";
System.out.println(Arrays.toString(test.split(",", -1))); // adds leading and trailing empty Strings .
// so effectively its like adding "" before , after and between each ","
String test1 = "aa,bb,cc";
System.out.println(Arrays.toString(test1.split(",",-1)));
}
O/P :
[, , , ] -- > Length =4
[aa, bb, cc]
To get the behavior you want you can just replace "," by " ,":
String test = ",,";
test = test.replace(",", " ,");
System.out.println((test.split(",").length));
With the split() function, java separates a String by the Substring of your choice. If there is nothing between them, the field will not be null, it will just be skipped.
In other programming languages, you could come across something like this:
String example = ',,,'
String[] example2 = example.split(',')
print(example2.length())
This could also deliver 4. Because there are 4 spaces around the ',' chars:
1,2,3,4

java split () method

I've got a string '123' (yes, it's a string in my program). Could anyone explain, when I use this method:
String[] str1Array = str2.split(" ");
Why I got str1Array[0]='123' rather than str1Array[0]=1?
str2 does not contain any spaces, therefore split copies the entire contents of str2 to the first index of str1Array.
You would have to do:
String str2 = "1 2 3";
String[] str1Array = str2.split(" ");
Alternatively, to find every character in str2 you could do:
for (char ch : str2.toCharArray()){
System.out.println(ch);
}
You could also assign it to the array in the loop.
str2.split("") ;
Try this:to split each character in a string .
Output:
[, 1, 2, 3]
but it will return an empty first value.
str2.split("(?!^)");
Output :
[1, 2, 3]
the regular expression that you pass to the split() should have a match in the string so that it will split the string in places where there is a match found in the string. Here you are passing " " which is not found in '123' hence there is no split happening.
Because there's no space in your String.
If you want single chars, try char[] characters = str2.toCharArray()
Simple...You are trying to split string by space and in your string "123", there is no space
This is because the split() method literally splits the string based on the characters given as a parameter.
We remove the splitting characters and form a new String every time we find the splitting characters.
String[] strs = "123".split(" ");
The String "123" does not have the character " " (space) and therefore cannot be split apart. So returned is just a single item in the array - { "123" }.
To do the "Split" you must use a delimiter, in this case insert a "," between each number
public static void main(String[] args) {
String[] list = "123456".replaceAll("(\\d)", ",$1").substring(1)
.split(",");
for (String string : list) {
System.out.println(string);
}
}
Try this:
String str = "123";
String res = str.split("");
will return the following result:
1,2,3

Java. How to remove white space on array

For example
I split a string "+name" by +. I got an white space" " and the "name" in the array(this doesn't happen if my string is "name+").
t="+name";
String[] temp=t.split("\\+");
the above code produces
temp[0]=" "
temp[1]=name
I only wants to get "name" without whitespace..
Also if t="name+" then temp[0]=name. I'm wondering what is difference between name+ and +name. Why do I get different output.
simply loop thru the items in array like the one below and remove white space
for (int i = 0; i < temp.length; i++){
temp[i] = if(!temp[i].trim().equals("") || temp[i]!=null)temp[i].trim();
}
The value of the first array item is not a space (" ") but an empty string (""). The following snippet demonstrates the behaviour and provides a workaround: I simply strip leading delimiters from the input. Note, that this should never be used for processing csv files, because a leading delimiter will create an empty column value which is usually wanted.
for (String s : "+name".split("\\+")) {
System.out.printf("'%s'%n", s);
}
System.out.println();
for (String s : "name+".split("\\+")) {
System.out.printf("'%s'%n", s);
}
System.out.println();
for (String s : "+name".replaceAll("^\\+", "").split("\\+")) {
System.out.printf("'%s'%n", s);
}
You get the extra element for "+name"'s case is because of non-empty value "name" after the delimiter.
The split() function only "trims" the trailing delimiters that result to empty elements at the end of an array. See JavaSE Manual.
Examples of .split("\\+") output:
"+++++" = { } // zero length array because all are trailing delimiters
"+name+" = { "", "name" } // trailing delimiter removed
"name+++++" = { "name" } // trailing delimiter removed
"name+" = { "name" } // trailing delimiter removed
"++name+" = { "", "", "name" } // trailing delimiter removed
I would suggest preventing to have those extra delimiters on both ends rather than cleaning up afterwards.
to remove white space
str.replaceAll("\\W","").
String yourString = "name +";
yourString = yourString.replaceAll("\\W", "");
yourArray = yourString.split("\\+");
For a one liner :
String temp[] = t.replaceAll("(^\\++)?(\\+)?(\\+*)?", "$2").split("\\+");
This will replace all multiple plus signs by one, or a plus sign at the start by empty String, and then split on plus signs.
Which will basically eliminate empty Strings in the result.
split(String regex) is equivalent to split(String regex, int limit) with limit = 0. And the documentation of the latter states :
If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.
Which is why a '+' at the start works differently than a '+' at the end
You might want to give guavas Splitter a try. It has a nice fluent api to deal with emptyStrings, trim(), etc.
#Test
public void test() {
final String t1 = "+name";
final String t2 = "name+";
assertThat(split(t1), hasSize(1));
assertThat(split(t1).get(0), is("name"));
assertThat(split(t2), hasSize(1));
assertThat(split(t2).get(0), is("name"));
}
private List<String> split(final String sequence) {
final Splitter splitter = Splitter.on("+").omitEmptyStrings().trimResults();
return Lists.newArrayList(splitter.split(sequence));
}

Categories

Resources