Extracting specific parts of a String - java

I am trying to get the "work" part of this string:
String test = "\prod\mp\incoming\users\work\test.java";
I have been trying to do it this way:
String result = test.substring(test.lastIndexOf("\\")+1 , test.length());
But this is returning "test.java"

try:
String test = "\\prod\\mp\\incoming\\users\\work\\test.java";
String[] s = test.split("\\");
result = s[s.length-2];
Here is the split method signature:
public String[] split(String regex);
It splits this string around matches of the given regular expression and returns an array of String containing the matches. In your case you need to get the second to last match which is the the match with index s.length-2 since the last element in the array s has the index s.length-1

Break your one-liners down into sensible parts. Instead of this...
String result = test.substring(test.lastIndexOf("\\") + 1 , test.length());
... try this...
int lastSlashIndex = test.lastIndexOf("\\");
int endIndex = test.length();
String result = test.substring(lastSlashIndex + 1, endIndex);
It then becomes painfully obvious that your substring goes from the last slash to the end of the string. So how do you fix it? First, you need to describe the problem properly. There are two possible things you are trying to do, and I have no idea which is correct:
You want to find the fifth item in the path.
You want to find the second to last item in the path.
I'll tackle the first, and if it turns out to be the second, you should be able to follow what I've done and do it yourself.
// Get the fifth item in the path
String[] items = test.split("\\");
String result = items[4];
Add some error checking to prevent an array index out of bounds exception.
String[] items = test.split("\\");
String result = "";
if (items.length > 4)
result = items[4];

Related

Java parsing last part of a string

I have three strings.
0:0:0-0:0:1
0:0:0-3:0:0-1:2:0
0:0:0-3:0:0-3:2:0-3:2:1
I am trying to do an exercise where I am parsing the string to output only the last part after the -, i.e. respectively:
0:0:1
1:2:0
3:2:1
I have tried of doing it by getting all the characters from the end of the string up until -5, but that won't always work (if the numbers are more then 1 integer). lastStateVisited is my string
lastStateVisited = lastStateVisited.substring(lastStateVisited.length() - 5);
I thought of splitting the string in an array and getting the last element of the array, but it seems inefficient.
String[] result = lastStateVisited.split("[-]");
lastStateVisited = result[result.length - 1];
What is a way I could do this? Thanks
Try this:
String l = "your-string";
int temp = l.lastIndexOf('-');
String lastPart = l.substring(temp+1);
Since your requirement concentrate around your need of acquiring the sub-string from the end till - appears first time.
So why not first get the index of last - that appeared in string. And after than extract the sub-string from here till end. Good option. :)
String str = "0:0:0-3:0:0-3:2:0-3:2:1";
String reqStr = str.substring(str.lastIndexOf('-')+1);
reqStr contains the required string. You can use loop with this part of code to extract more such strings.

Replace parts of a string in Java

I need to replace parts of a string by looking up the System properties.
For example, consider the string It was {var1} beauty killed {var2}
I need to parse the string, and replace all the words contained within the parenthesis by looking up their value in System properties. If System.getProperty() returns null, then simply replace with empty character. This is pretty straightforward when I know the variables well ahead. But the string that I need to parse is not defined ahead. I wouldn't know how many number of variables are in the string and what the variable names are. Assuming a simple, well formatted string (no nested parenthesis, open - close matches), what is the simplest or the most elegant way to parse through the string and replace all the character sequences that are enclosed in the parenthesis?
Only solution I could come up with is to traverse the string from the first character, note down the positions of the start and end positions of the parenthesis, replace the string between them, and then continue until reaching the end of the string. Is there simpler way to do this?
You can use the parentheses to break the initial string into substrings, and then replace every other substring.
String[] substituteValues = {"the", "str", "other", "another"};
int substituteValuesIndex = 0;
String test = "Here is {var1} string called {var2}";
// split the string up into substrings
test = test.replaceAll("\\}", "\\{");
String[] splitString = test.split("\\{");
// now sub in your values
for (int k=1; k < splitString.length; k = k+2) {
splitString[k] = substituteValues[substituteValuesIndex];
substituteValuesIndex++;
}
String result = "";
for (String s : splitString) {
result = result + s;
}

How to get in String from String Array by Split in Java Android

This is my Result where i got response from server that I want to get by Soap.I can parse this value by JSON but I'm having a problem doing so as I wish to get this value split.
Result=1~Saved successfully~{ "TABLE":[{ "ROW":[ { "COL":{ "UserID":"30068"}} ]}]}
I am using this code to get UserId values in tmpVal, however am not obtaining my desired results.
String tmpVal = returnValue.toString().split("~")[3];
String tmpVal = returnValue.toString().split("~")[3];
This would give you the 4th String in the array produced by split, but since split only produced an array of 3 Strings, this code gives you an exception.
If you want to get the last part of the split response - { "TABLE":[{ "ROW":[ { "COL":{ "UserID":"30068"}} ]}]} - you need returnValue.toString().split("~")[2].
Of course, it would be safer to first test how many Strings were returned by split :
String[] splitResult = returnValue.toString().split("~");
if (splitResult.length > 2) {
tempVal = splitResult[2];
}
As stated above in the comment section, Arrays start with index 0, thus if you have an array with 3 elements, the index are 0..1..2 and not 1..2..3
All you have to do is change the String tmpVal = returnValue.toString().split("~")[3]; to:
String tmpVal = returnValue.toString().split("~")[2];
As that will obtain the 3rd element instead of the fourth element as you've been trying to do.
You may also check out this question

Getting the last part of the string

I have a string :
"id=40114662&mode=Edit&reminderId=44195234"
All i want from this string is the final number 44195234. I can't use :
String reminderIdFin = reminderId.substring(reminderId.lastIndexOf("reminderId=")+1);
as i cant have the = sign as the point it splits the string. Is there any other way ?
Try String.split(),
reminderIdFin.split("=")[3];
You can use indexOf() method to get where this part starts:
int index = reminderIdFin.indexOf("Id=") + 3;
the plus 3 will make it so that it jumps over these characters. Then you can use substring to pull out your wanted string:
String newString = reminderIdFin.substring(index);
Remove everything else and you'll be left with your target content:
String reminderIdFin = reminderId.replaceAll(".*=", "");
The regex matches everything up to the last = (the .* is "greedy").

Finding the longest substring between a "start" string and one of 3 possible "end" strings

So my question is substring-related.
How do you find the longest possible substring between a starting string and one of three ending strings? I also need to find the index of the original string that the largest substring starts at.
So:
Start string:
"ATG"
3 possible end strings:
"TAG"
"TAA"
"TGA"
An example original string might be:
"SDAFKJDAFKATGDFSDFAKJDNKSJFNSDTGASDFKJSDNKFJSNDJFATGDSDFKJNSDFTAGSDFSDATGFF"
So the result of that should give me:
- Longest substring length: 23 (from the substring ATGDFSDFAKJDNKSJFNSDTGA)
- Index of longest substring: 10
I cannot use Regex.
Thanks for any help!
This is arguably the easiest way, and it's just one line:
String target = str.replaceAll(".*ATG(.*)(TAG|TAA|TGA).*", "$1");
To find the index:
int index = str.indexOf("ATG") + 3;
Note: I have interpreted your remark "I cannot use regex" to mean "I am unskilled at regex", because if it's a java question, regex is available.
Well, this looks like a fun one.
It seems the most straightforward way to do this would be to build your own mini finite state machine. You would have to parse each character in the string and keep track of all possible character sequences that would terminate the sequence.
If you hit a 'T', you need to jump ahead and look at the next character. If it's an 'A' or a 'G' you need to jump ahead again, otherwise, add those tokens to your string. Continue the pattern until you get to the end of the original string, or match one of your terminal patterns.
So, maybe something that looks like this (simplified example):
String longestSequence(String original) {
StringBuilder sb = new StringBuilder();
char[] tokens = original.toCharArray();
for (int i = 0; i < tokens.length; ++i) {
// read each token, and compare / look ahead to see if you should keep going or terminate.
}
return sb.toString();
}
match your string to this regex:
ATG[A-Z]+(TAG|TAA|TGA)
if multiple match occurs then iterate and keep the one with highest length.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
// using pattern with flags
Pattern pattern = Pattern.compile("ATG[A-Z]+(TAG|TAA|TGA)");
Matcher matcher = pattern.matcher( yourInputStringHere );
while (matcher.find()) {
System.out.println("Found the text \"" + matcher.group()
+ "\" starting at " + matcher.start()
+ " and ending at index " + matcher.end());
}
There are already some beautiful and elegant solutions to your problem (Bohemian and inquisitive). If you still - as originally stated - can't use regex, here's an alternative. This code is not especially elegant, and as pointed, there are better ways to do it, but it should at least clearly show you the logic behind the solution to your problem.
How do you find the longest possible substring between a starting string
and one of three ending strings?
First, find the index of starting string, then find the index of each ending string, and get substrings for each ending, then their length. Remember that if string is not found, its index will be -1.
String originalString = "SDAFKJDAFKATGDFSDFAKJDNKSJFNSDTGASDFKJSDNKFJSNDJFATGDSDFKJNSDFTAGSDFSDATGFF";
String STARTING_STRING = "ATG";
String END1 = "TAG";
String END2 = "TAA";
String END3 = "TGA";
//let's find the index of STARTING_STRING
int posOfStartingString = originalString.indexOf(STARTING_STRING);
//if found
if (posOfStartingString != -1) {
int tagPos[] = new int[3];
//let's find the index of each ending strings in the original string
tagPos[0] = originalString.indexOf(END1, posOfStartingString+3);
tagPos[1] = originalString.indexOf(END2, posOfStartingString+3);
tagPos[2] = originalString.indexOf(END3, posOfStartingString+3);
int lengths[] = new int[3];
//we can now use the following methods:
//public String substring(int beginIndex, int endIndex)
//where beginIndex is our posOfStartingString
//and endIndex is position of each ending string (if found)
//
//and finally, String.length() to get the length of each substring
if (tagPos[0] != -1) {
lengths[0] = originalString.substring(posOfStartingString, tagPos[0]).length();
}
if (tagPos[1] != -1) {
lengths[1] = originalString.substring(posOfStartingString, tagPos[1]).length();
}
if (tagPos[2] != -1) {
lengths[2] = originalString.substring(posOfStartingString, tagPos[2]).length();
}
} else {
//no starting string in original string
}
lengths[] table now contains length of strings starting with STARTING_STRING and 3 respective endings. Then just find which one is the longest and you will have your answer.
I also need to find the index of the original string that the largest substring starts at.
This will be the index of where starting string starts, in this case 10.

Categories

Resources