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.
Related
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;
}
I'm trying to get the last three characters in a string. With the following code, I'm trying to get the last three characters of the fname variable, but I'm getting a "The method Length(int) is undefined for the type String" error:
String fname = request.getParameter("fname");
String lname = request.getParameter("lname");
String number = request.getParameter("number");
String firstPart = lname.substring(0, 3);
String middlePart = fname.substring(0, fname.Length(3));
So there are two problems here:
Firstly you're calling fname.Length(3), which doesn't make sense as String doesn't have a Length(int n) method on it. What it does have is a substring(int) method and a length() method, which you can use as follows:
String middlePart = fname.substring(fname.length() - 3);
As outlined in the linked JavaDocs, String.substring() "Returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.". So if we can provide it with the index (or position) within the String fname where we want to start copying from.
If I've got a String such as "Chicken", and I want the last 3 characters, I'd call "Chicken".substring(4), and the result would be "ken" (Strings are zero-indexed, so the character 'k' has index 4).
Instead of hard coding the index where I want to start the substring from, I use the String.length() method which tells me how long a String is, and subtract 3. In the above example, "Chicken".length() is 7, and so "Chicken".length() - 3 is the index where you should start substring-ing if you want the last 3 characters.
String lastThreeChars = string.substring(string.length() - 3);
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];
I've imported a file and turned it into a String called readFile. The file contains two lines:
qwertyuiop00%
qwertyuiop
I have already extracted the "00" from the string using:
String number = readFile.substring(11, 13);
I now want to extract the "ert" and the "uio" in "qwertyuiop"
When I try to use the same method as the first, like so:
String e = readFile.substring(16, 19);
String u = readFile.substring(20, 23);
and try to use:
System.out.println(e + "and" + u);
It says string index out of range.
How do I go about this?
Is it because the next two words I want to extract from the string are on the second line?
If so, how do I extract only the second line?
I want to keep it basic, thanks.
UPDATE:
it turns out only the first line of the file is being read, does anyone know how to make it so it reads both lines?
If you count the total number of characters for each string, they are more than the indexes your entering.
qwertyuiop00% is 13 characters. Call .length() method on the string to verify the length is the one you expect.
I would debug with adding the following before:
System.out.println(readFile);
System.out.println(readFile.length());
Note:
qwertyuiop00% qwertyuiop is 24 characters since space counts as a character. Unless ofcourse you don't have the space in which it's 23 characters and your indexes are 0 to 22
Note2:
I asked for the parser code since I suspect your using the usual code which is something like:
while ((line = reader.readLine()) != null)
You need to concatenate those lines into one String (though it's not the best approach).
see: How do I create a Java string from the contents of a file?
First split your string into lines, you could do this using
String[] lines = readFile.split("[\r\n]+");
You may want to read the content directly into a List<String> using Files.#readAllLines instead.
second, do not use hard coded indexes, use String#indexOf to find them out. If a substring does not occur in your original string, then the method retunrs -1, always check for that value and call substring only when the return value is not -1 (0 or greater).
if(lines.length > 1) {
int startIndex = lines[1].indexOf("ert");
if(startIndex != -1) {
// do what you want
}
}
Btw, there is no point in extracting already known substring from a string
System.out.println(e + "and" + u);
is equivalent to
System.out.println("ertanduio");
Knowing the start and end position of a fixed substring makes only sence if you want to do something with rest of original string, for example removing the substrings.
You may give this a try:-
Scanner sc=new Scanner(new FileReader(new File(The file path for readFile.txt)));
String st="";
while(sc.hasNext()){
st=sc.next();
}
System.out.println(st.substring(2,5)+" "+"and"+" "+st.substring(6,9));
Check out if it works.
Alright so here is my problem. Basically I have a string with 4 words in it, with each word seperated by a #. What I need to do is use the substring method to extract each word and print it out. I am having trouble figuring out the parameters for it though. I can always get the first one right, but the following ones generally have problems.
Here is the first piece of the code:
word = format.substring( 0 , format.indexOf('#') );
Now from what I understand this basically means start at the beginning of the string, and end right before the #. So using the same logic, I tried to extract the second word like so:
wordTwo = format.substring ( wordlength + 1 , format.indexOf('#') );
//The plus one so I don't start at the #.
But with this I continually get errors saying it doesn't exist. I figured that the compiler was trying to read the first # before the second word, so I rewrote it like so:
wordTwo = format.substring (wordlength + 1, 1 + wordLength + format.indexOf('#') );
And with this it just completely screws it up, either not printing the second word or not stopping in the right place. If I could get any help on the formatting of this, it would be greatly appreciated. Since this is for a class, I am limited to using very basic methods such as indexOf, length, substring etc. so if you could refrain from using anything to complex that would be amazing!
If you have to use substring then you need to use the variant of indexOf that takes a start. This means you can start look for the second # by starting the search after the first one. I.e.
wordTwo = format.substring ( wordlength + 1 , format.indexOf('#', wordlength + 1 ) );
There are however much better ways of splitting a string on a delimiter like this. You can use a StringTokenizer. This is designed for splitting strings like this. Basically:
StringTokenizer tok = new StringTokenizer(format, "#");
String word = tok.nextToken();
String word2 = tok.nextToken();
String word3 = tok.nextToken();
Or you can use the String.split method which is designed for splitting strings. e.g.
String[] parts = String.split("#");
String word = parts[0];
String word2 = parts[1];
String word3 = parts[2];
You can go with split() for this kind of formatting strings.
For instance if you have string like,
String text = "Word1#Word2#Word3#Word4";
You can use delimiter as,
String delimiter = "#";
Then create an string array like,
String[] temp;
For splitting string,
temp = text.split(delimiter);
You can get words like this,
temp[0] = "Word1";
temp[1] = "Word2";
temp[2] = "Word3";
temp[3] = "Word4";
Use split() method to do this with "#" as the delimiter
String s = "hi#vivek#is#good";
String temp = new String();
String[] arr = s.split("#");
for(String x : arr){
temp = temp + x;
}
Or if you want to exact each word... you have it already in arr
arr[0] ---> First Word
arr[1] ---> Second Word
arr[2] ---> Third Word
I suggest that you've a look at the Javadoc for String before you proceed further.
Since this is your homework, I'll give you a couple of hints and maybe you can solve it yourself:
The format for subString is public void subString(int beginIndex, int endIndex). As per the javadoc for this method:
Returns a new string that is a substring of this string. The substring
begins at the specified beginIndex and extends to the character at
index endIndex - 1. Thus the length of the substring is
endIndex-beginIndex.
Note that if you've to use this method, understand that you'll have to shift your beginIndex and endIndex each time because in your situation, you'll have multiple words that are separated by #.
However if you look closely, there's another method in String class that might be helpful to you. That's the public String[] split(String regex) method. The javadoc for this one states:
Splits this string around matches of the given regular expression.
This method works as if by invoking the two-argument split method with
the given expression and a limit argument of zero. Trailing empty
strings are therefore not included in the resulting array.
The split() method looks pretty interesting for your case. You can split your String with the delimiter that you have as the parameter to this method, get the String array and work with that.
Hope this helps you to understand your problem and get started towards a solution :)
Since this is a home work, it may be better to have try to write it your self. But I will give a clue.
Clue:
The indexOf method has another overload: int indexOf(int chr,
int fromIndex) which find the first character chr in the string
from the fromIndex.
http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html
From this clue, the program will look something like this:
Find the index of the first '#' from the start of the string.
Extract the word from 0th character to that index.
Find the index of the first '#' from the character AFTER the first '#'.
Extract the word from the first '#' that index.
... Just do it until you get 4 words or the string ends.
Hope this helps.
I don't know why you're forced to use String#substring, but as others have mentioned, it seems like the wrong method for the kind of functionality you need.
String#split(String regex) is what you would use for such a problem, or, if your input sequence is something you don't control, I would suggest you look at the overloaded method String#split(String regex, int limit); this way you can impose a limit on the amount of matches you make, controlling your resulting array.