I have a String and I want to get the words before and after the " - " (dash). How can I do that?
example:
String:
"First part - Second part"
output:
first: First part
second: Second part
With no error-checking or safety, this could work:
String[] parts = theString.split("-");
String first = parts[0];
String second = parts[1];
Easy: use the String.split method.
Example :
final String s = "Before-After";
final String before = s.split("-")[0]; // "Before"
final String after = s.split("-")[1]; // "After"
Note that I'm leaving error-checking and white-space trimming up to you!
int indexOfDash = s.indexOf('-');
String before = s.substring(0, indexOfDash);
String after = s.substring(indexOfDash + 1);
Reading the javadoc helps finding answers to such questions.
#Test
public void testSplit() {
String str = "First part - Second part";
String strs[] = str.split("-");
for (String s : strs) {
System.out.println(s);
}
}
Output:
First part
Second part
use indexOf() and substring() method of String class, for the example given you can also use split() method
Related
I have a string sub1-sub2-sub3 which I want to split from right to left. Currently I am using split function like this which splits the string from left to right -
String str = "sub1-sub2-sub3";
System.out.println("Result :" + str.split("-", 2));
Elements in output :
sub1
sub2-sub3
Desired output :
sub1-sub2
sub3
Is there a way where I can split my string on - starting from right?
You could do a regex split on -(?!.*-):
String str = "sub1-sub2-sub3";
String[] parts = str.split("-(?!.*-)");
System.out.println(Arrays.toString(parts)); // [sub1-sub2, sub3]
The regex pattern used here will only match the final dash.
A generic solution as utility method that takes limit as input with java 8:
public List<String> splitReverse(String input, String regex, int limit) {
return Arrays.stream(reverse(input).split(regex, limit))
.map(this::reverse)
.collect(Collectors.toList());
}
private String reverse(String i){
return new StringBuilder(i).reverse().toString();
}
reverse() code taken from here
Input: sub1-sub2-sub3
Reverse input: 3bus-2bus-1bus
Split(rev,2): [3bus] , [2bus-1bus]
Reverse each: [sub3] , [sub1-sub2]
One way would be to reverse the string before the split and then reverse the resulting strings.
String str = "sub1-sub2-sub3";
Arrays.stream(StringUtils.reverse(str).split("-",2))
.map(StringUtils::reverse)
.forEach(System.out::println);
Output:
sub3
sub1-sub2
It won't yield the same result as requested but maybe it will help.
P.S. util class used is from apache: org.apache.commons.lang3.StringUtils
A quick and dirty solution i cam up with would be
String str = "sub1-sub2-sub3";
str = StringUtils.reverse(str);
String[] split = str.split("-", 2);
split[0] = StringUtils.reverse(split[0]);
split[1] = StringUtils.reverse(split[1]);
System.out.println("Result :" + split[0] + " #### " + split[1]);
another way would be java how to split string from end
The below solution worked for me fine :
str.substring(0, str.lastIndexOf("-"));
str.substring(str.lastIndexOf("-"));
I have a string as follows:
"[error=<null>,EntityID=105378032, Context=<null>]"
and i want to extract the EntityID( in this case 105378032), but i want a generalize solution of doing it.
What is the most efficient way of doing it.
I don't want to traverse the string and get that part.
Did you try regex like .*EntityID=(.*?),.* which mean get the group of characters between EntityID= and the next comma , using replaceAll :
String str = "[error=,EntityID=105378032, Context=]";
System.out.println(str.replaceAll(".*EntityID=(.*?),.*", "$1"));// output 105378032
regex demo
Using Regular expressions seems to be the best way out.
This code works:
String str = "[error=,EntityID=105378032, Context=]";
String[] arr = str.split("EntityID="); //splits it on the part "EntityID="
String[] arr1 = arr[1].split(","); // splits it on the next comma in the 'right' half of your string.
System.out.println(arr1[0]); //prints the 'left' half before the comma.
Ideone link here.
Hope this helps!
You can use this method it's work like a charm
public static String getSubString(String mainString, String lastString, String startString) {
String endString = "";
int endIndex = mainString.indexOf(lastString);
int startIndex = mainString.indexOf(startString);
endString = mainString.substring(startIndex, endIndex);
return endString;
}
Result:
String resultStr = getSubString(yourFullString,",Context","EntityID=");
Happy codding.
I need to extract the amount in a string below, I need the string of "1.50",
eg. CARD,S1234,1.50
I try to use indexOf, but then there might be few commas. If I use . for reference, the amount might be 100.50. Either way is not working.
Any idea?
String.split (",") - get last element of the returned array:
String str = "CARD,S1234,1.50";
String arr[] = str.split (",");
System.out.println(arr[arr.length -1]);
Use the .split() method:
String[] arrayString = "CARD,S1234,1.50".split(",");
String lastString = arrayString[arrayString.length - 1];
String s = "CARD,S1234,1.50";
String last = s.substring(s.lastIndexOf(",")+1, s.length);
I want to parse the following and store it as a new string, with the condition that mawi is stored and everything else is removed.
<ns0:Assignee>mawi - Manfred Wilson</ns0:Assignee>
One solution I suppose could be a substring starting with the first character after the first > and ending two characters before the first -. All the data is identical. The result is a String with value mawi.
String initial = "<ns0:Assignee>mawi - Manfred Wilson</ns0:Assignee>";
String substring = initial.substring(example.indexOf(">"));
Not sure where to go from here... Any thoughts?
Although the below code do the trick, I suggest you to use Jsoup or XML Parse if you are processing multiple strings like this
Pattern pattern = Pattern.compile("<ns0:Assignee>(.+?)</ns0:Assignee>");
Matcher matcher = pattern.matcher("<ns0:Assignee>mawi - Manfred Wilson</ns0:Assignee>");
matcher.find();
String result = matcher.group(1);
String finalString = result.split(" - ")[0];
System.out.println(finalString); // mawi
If all the strings are built like your example string, you could go with this:
initial.substring(initial.indexOf('>') + 1, initial.indexOf(' '));
Note the + 1 at the start index.
When your Strings are more complicated, I would recommend either using a library for working with XML or using Regular Expressions.
So now you got substring which is equal to: >mawi - Manfred Wilson</ns0:Assignee>.
Now, you can substring your substring again to find only mawi, like this;
String initial = "<ns0:Assignee>mawi - Manfred Wilson</ns0:Assignee>";
String midSub = initial.substring(initial.indexOf('>'));
String finalSub = midSub.substring(1, midSub.indexOf(' ')); // 1 because we still have `>`
System.out.println(finalSub);
Or, one liner:
String finalSub = initial.substring(initial.indexOf('>')+1, initial.indexOf(' '));
show this:
String s = "<ns0:Assignee>mawi - Manfred Wilson</ns0:Assignee>";
s = s.substring(s.indexOf("<ns0:Assignee>")+"<ns0:Assignee>".length(), s.indexOf("</ns0:Assignee>"));
public class string {
public static void main(String[] args) {
String s = "<ns0:Assignee>mawi - Manfred Wilson</ns0:Assignee>";
s = s.substring(14, 18);
System.out.println(s);
}
}
I am looking to remove parts of a string if it ends in a certain string.
An example would be to take this string: "am.sunrise.ios#2x.png"
And remove the #2x.png so it looks like: "am.sunrise.ios"
How would I go about checking to see if the end of a string contains "#2x.png" and remove it?
You could check the lastIndexOf, and if it exists in the string, use substring to remove it:
String str = "am.sunrise.ios#2x.png";
String search = "#2x.png";
int index = str.lastIndexOf(search);
if (index > 0) {
str = str.substring(0, index);
}
Assuming you have a string initialized as String file = "am.sunrise.ios#2x.png";.
if(file.endsWith("#2x.png"))
file = file.substring(0, file.lastIndexOf("#2x.png"));
The endsWith(String) method returns a boolean determining if the string has a certain suffix. Depending on that you can replace the string with a substring of itself starting with the first character and ending before the index of the character that you are trying to remove.
private static String removeSuffixIfExists(String key, String suffix) {
return key.endswith(suffix)
? key.substring(0, key.length() - suffix.length())
: key;
}
}
String suffix = "#2x.png";
String key = "am.sunrise.ios#2x.png";
String output = removeSuffixIfExists(key, suffix);
public static void main(String [] args){
String word = "am.sunrise.ios#2x.png";
word = word.replace("#2x.png", "");
System.out.println(word);
}
If you want to generally remove entire content of string from # till end you can use
yourString = yourString.replaceAll("#.*","");
where #.* is regex (regular expression) representing substring starting with # and having any character after it (represented by .) zero or more times (represented by *).
In case there will be no #xxx part your string will be unchanged.
If you want to change only this particular substring #2x.png (and not substirng like #3x.png) while making sure that it is placed at end of your string you can use
yourString = yourString.replaceAll("#2x\\.png$","");
where
$ represents end of string
\\. represents . literal (we need to escape it since like shown earlier . is metacharacter representing any character)
Since I was trying to do this on an ArrayList of items similarly styled I ended up using the following code:
for (int image = 0; image < IBImages.size(); image++) {
IBImages.set(image, IBImages.get(image).split("~")[0].split("#")[0].split(".png")[0]);
}
If I have a list of images with the names
[am.sunrise.ios.png, am.sunrise.ios#2x.png, am.sunrise.ios#3x.png, am.sunrise.ios~ipad.png, am.sunrise.ios~ipad#2x.png]
This allows me to split the string into 2 parts.
For example, "am.sunrise.ios~ipad.png" will be split into "am.sunrise.ios" and "~ipad.png" if I split on "~". I can just get the first part back by referencing [0]. Therefore I get what I'm looking for in one line of code.
Note that image is "am.sunrise.ios~ipad.png"
You could use String.split():
public static void main(String [] args){
String word = "am.sunrise.ios#2x.png";
String[] parts = word.split("#");
if (parts.length == 2) {
System.out.println("looks like user#host...");
System.out.println("User: " + parts[0]);
System.out.println("Host: " + parts[1]);
}
}
Then you haven an array of Strings, where the first element contains the part before "#" and the second element the part after the "#".
Combining the answers 1 and 2:
String str = "am.sunrise.ios#2x.png";
String search = "#2x.png";
if (str.endsWith(search)) {
str = str.substring(0, str.lastIndexOf(search));
}