How to split string in two parts - java

I'm retrieving Strings from the database and storing in into a String variable which is inside the for loop. Few Strings i'm retrieving are in the form of:
https://www.ppltalent.com/test/en/soln-computers-ltd
and few are in the form of
https://www.ppltalent.com/test/ja/aman-computers-ltd
I want split string into two substrings i.e
https://www.ppltalent.com/test/en/soln-computers-ltd as https://www.ppltalent.com/test/en and /soln-computers-ltd.
It can easily be separated if i would have only /en.
String[] parts = stringPart.split("/en");
System.out.println("Divided String : "+ parts[1]);
But in many of the strings it has /jr , /ch etc.
So how can I split them in two sub-strings?

You could perhaps use the fact that /en and /ja are both preceeded by /test/. So, something like indexOf("/test/") and then substring.
In your examples, it seems like you're interested in the very last part, which could be retrieved by lastIndexOf('/') for instance.
Or, using look-arounds you could do
String s1 = "https://www.ppltalent.com/test/en/soln-computers-ltd";
String[] parts = s1.split("(?<=/test/../)");
System.out.println(parts[0]); // https://www.ppltalent.com/test/er/
System.out.println(parts[1]); // soln-computers-ltd

Split on the last /
String fullUrl = "https:////www.ppltalent.com//test//en//soln-computers-ltd";
String baseUrl = fullUrl.substring(0, fullUrl.lastIndexOf("//"));
String manufacturer = fullUrl.subString(fullUrl.lastIndexOf("//"));

Related

String equation separation

String Str = new String("(300+23)*(43-21)/(84+7)");
System.out.println("Return Value :" );
String[] a=Str.split(Str);
String a="("
String b="300"
String c="+"
I want to convert this single string to an array giving output as above till the end of the equation using split method any suggestions
The above code doesn't works for it
When you write Str.split(Str); , the parameter of the split function should be the string by which you want to break the bigger string into an array of smaller strings.
For example,
String s = "this is a string";
String [] array = s.split(" ");
The parameter for the split function here is basically just a space, so the split function will break the s string into parts delimited by the " " spring, which will result in array having the following values: {"this", "is", "a", "string"}.
I think this example is conclusive. What you are doing in your code is basically trying to break your string into parts using the string itself, which of course makes no sense.
You won't find an answer to what you want to achieve using just the split function, because there is no good string to act like a token by which to delimit the bigger string.
You could use a simple regular expression to achieve what you want, e.g.
public static void main(final String[] args) {
final String string = "(300+23)*(43-21)/(84+7)";
final String[] arr = string.split("(?<![\\d.])|(?![\\d.])");
for (final String s : arr)
System.out.println(s);
}
Has to be modified a bit if whitespace could be present etc. but works for your example input string.

Get specific value from string using split fucntion

I have String something like this
APIKey testapikey=mysecretkey
I want to get mysecretkey to String attribute
What i tried is below
String[] couple = string.split(" ");
String[] values=couple[1].split("=");
String mykey= values[1];
Is this right way?
You could use the String.replaceAll(...) method.
String string = "APIKey testapikey=mysecretkey";
// [.*key=] - match the substring ending with "key="
// [(.*)] - match everything after the "key=" and group the matched characters
// [$1] - replace the matched string by the value of cpaturing group number 1
string = string.replaceAll(".*key=(.*)", "$1");
System.out.println(string);
Don't use split() you will be unnecessarily creating an array of Strings.
Use String myString = originalString.replaceAll(".*=","");
I think using split here is pretty error prone. A small change in the format of the incoming string (such as a space being added) could result in a bug that's hard to diagnose. My recommendation would be to play it safe and use a regular expression to ensure the text is exactly as you expect:
Pattern pattern = Pattern.compile("APIKey testapikey=(\\w*)");
Matcher matcher = pattern.matcher(apiKeyText);
if (!matcher.matches())
throw new IllegalArgumentException("apiKey does not match pattern");
String apiKey = matcher.group();
That code documents your intentions much better than use of split and picks up unexpected changes in format. The only possible downside is performance but assuming you make pattern a static final (to ensure it's compiled once) then unless you are calling this millions of times then I very much doubt it will be an issue.

Splitting a comma separated string and discarding some values in the string

Given the following string:
423545(50),[7568787(50)],53654656,2021947(50),[021947],2021947(50),[8021947(50)]
I would like to split it and put the contents in a array excluding the square brackets and the numbers in the brackets - i.e the result should be an array that contains the following.
{423545,7568787,53654656,2021947,021947,2021947,8021947}
My attempt so far only works if there are no square brackets:
String str = "342398789, [233434],423545(50),[7568787(500)],53654656,2021947(50),[021947],2021947(150),[8021947(50)]";
String[] listItems = str.split("(\\(\\d+\\))?(?:,|$)")
How can I update the above regex to also extract the numbers that wrapped in square brackets?
The strings I am trying to extract are identifiers for database rows so i need to extract them to retrieve the database row.
You could try this way
String str = "[342398789], [233434] ,423545(50),[7568787(500)],"
+ "53654656,2021947(50),[021947],2021947(150),[8021947(50)]";
String[] listItems = str.replaceFirst("^\\[", "").split(
"(\\(\\d+\\))?\\]?(\\s*,\\s*\\[?|$)");
System.out.println(Arrays.toString(listItems));
output
[342398789, 233434, 423545, 7568787, 53654656, 2021947, 021947, 2021947, 8021947]
try this way:
String str = "342398789, [233434],423545(50),[7568787(500)],53654656,2021947(50),[021947],2021947(150),[8021947(50)]";
String[] listItems = str.replaceAll("\\(\\d+\\)","")replaceAll("\\[","").replaceAll("\\]","").split(",");

string split to string array

I have a string variable Result that contains a string like:
"<field1>text</field1><field2>text</field2> etc.."
I use this code to try to split it:
Result = Result.replace("><", ">|<");
String[] Fields = Result.split("|");
According to the many websites, including this one, this should give me an array like this:
Fields[0] = "<field1>text</field2>"
Fields[1] = "<field2>test</field2>"
etc...
But it gives me an array like:
Fields(0) = ""
Fields(1) = "<"
Fields(2) = "f"
Fields(3) = "i"
Fields(4) = "e"
etc..
So, what am I doing wrong?
Your call to split("|") is parsing | as a regular-expression-or, which on its own will split between every character.
You can regex-escape the character to prevent this from occurring, or use a different temporary split character altogether.
String[] fields = result.split("\\|");
or
result = result.replace("><", ">~<");
String[] fields = result.split("~");
Try doing
String[] fields = result.split("\\|");
Note that I've used more conventional variable names (they shouldn't start with capital letters).
Remember that the split methods takes a regular expression as an argument, and | has a specific meaning in the world of regular expressions, which is why you're not receiving what you were expecting.
Relevant documentation:
split

How do I split text by "," and get rid of the "," in java?

I want to split and get rid of the comma's in a string like this that are entered into a textfield:
1,2,3,4,5,6
and then display them in a different textfield like this:
123456
here is what i have tried.
String text = jTextField1.getText();
String[] tokens = text.split(",");
jTextField3.setText(tokens.toString());
Can't you simply replace the , ?
text = text.replace(",", "");
If you're going to put it back together again, you don't need to split it at all. Just replace the commas with the empty string:
jTextField3.setText(text.replace(",", ""));
Assuming this is what you really want to do (e.g. you need to use the individual elements somewhere before concatenating them) the following snippet should work:
String s1 = "1,2,3,4,5,6";
String ss[] = s1.split(",", 0);
StringBuilder sb = new StringBuilder();
for (String s : ss) {
// Use each element here...
sb.append(s);
}
String s2 = sb.toString(); // 123456
Note that the String#split(String) method in Java has strange default behavior so using the method that takes an additional int parameter is recommended.
I may be wrong, but I believe that call to split will get rid of the commas. And it should leave tokens an array of just the numbers

Categories

Resources