Java String split with   as pameter - java

I read a html file parser. Jsoup.parse(new File("2005-08.html"), "ISO-8859-1"); and then I need to split a string like "+24 -2" into two: "+24" and "-2". Then I pass this string to System.out.println() it prints as whitespase. I tried
s.split(" ");
s.split(" ");
but nothing works. I get one string "+24 -2".

You say your input is +24 -2 and you want to split it into +24 and -2.
Well that is pretty easy and it uses the same technique than your tried with:
String s = "+24 -2";
// The correct delimiter begins with an '&'
String[] result = s.split(" ");
// Print the result
System.out.println(Arrays.toString(result));
The output is [+24, -2]. You can access the results by result[0] which yields +24 and result[1] which is -2.
If you like you can also parse them as Integer by using:
int firstValue = Integer.parseInt(result[0]);
int secondValue = Integer.parseInt(result[1]);

Related

how to parse integer from a long string

I want to parse two values from a string in android studio.
I cannot change the data type from web so I need to parse an Intt.The string that I receive from web is
5am-10am.
How can I get these values i.e. 5 and 10 from the string "5am-10am".
Thanks in advance for help.
its work only this kind of format "Xam-Yam".
String value="5am-10am";
value.replace("am","");
value.replace("pm","");//if your string have pm means add this line
String[] splited = value.split("-");
//splited[0]=5
//splited[1]=10
Here is the trick you should use:-
String timeValue="5am-10am";
String[] timeArray = value.split("-");
// timeArray [0] == "5am";
// timeArray [1] == "10am";
timeArray [0].replace("am","");
// timeArray [0] == "5";// what u needed
timeArray [1].replace("am","");
// timeArray [1] == "10"; // what u needed
So, the code below shows step by step how to parse the format you are given. I also added in the steps to use the newly parsed Strings as ints so you can perform arithmetic on them. Hope this helps.
`/*Get the input*/
String input = "5am-10am"; //Get the input
/*Separate the first number from the second number*/
String[] values = input.split("-"); //Returns 'values[5am, 10am]'
/*Not the best code -- but clearly shows what to do*/
values[0] = values[0].replaceAll("am", "");
values[0] = values[0].replaceAll("pm", "");
values[1] = values[1].replaceAll("am", "");
values[1] = values[1].replaceAll("pm", "");
/*Allows you to now use the string as an integer*/
int value1 = Integer.parseInt(values[0]);
int value2 = Integer.parseInt(values[1]);
/*To show it works*/
int answer = value1 + value2;
System.out.println(answer); //Outputs: '15'`
I will use some regex to remove the other String and leave only the numeric data. sample code below:
public static void main(String args[]) {
String sampleStr = "5am-10pm";
String[] strArr = sampleStr.split("-"); // I will split first the two by '-' symbol.
for(String strTemp : strArr) {
strTemp = strTemp.replaceAll("\\D+",""); // I will use this regex to remove all the string leaving only numbers.
int number = Integer.parseInt(strTemp);
System.out.println(number);
}
}
The advantages of this is you don't need to specifically remove "am" or "pm" because all of the other character will be remove and the numbers will only be left.
I think that this way can be the faster. Please consider that the regex doesn't validates so it will parse values as "30am-30pm" for example. Validation comes apart.
final String[] result = "5am-10pm".replaceAll("(\\d)[pa]m", "$1").split("-");
System.out.println(result[0]); // -- 5
System.out.println(result[1]); // -- 10

Splitting a string from url pattern

I have a string in the format: /constant/variableurl . What is the best way out, such that, I can get the variableurl alone as a string.
I understand string tokenizer and regex are the two way out, but not sure how to split the last variableurl alone.
Any help is appreciated.
According to your explanation and example this is code that you could use (not perfect, generic)
toFind.substring(toFind.lastIndexOf("/") + 1)
where
String toFind = "/constant/variableurl"
There are many ways to achieve that:
String[] res = myStr.split("\\/");
String myStr = res[res.length - 1];
myStr = myStr.substring(myStr.lastIndexOf('/') + 1);
...
To add more methods, visit the docs.
If the constant portion of the string is the same for all your strings, you can get the variable portion of it using substring, and passing the length of the common part:
String a = "/constant/hello/world";
String b = "/constant/quick/brown/fox";
String c = "/constant/jumps/over/the/lazy/dog";
int len = "/constant/".length(); // That's 10
a = a.substring(len); // Becomes "hello/world"
b = a.substring(len); // Becomes "quick/brown/fox"
c = a.substring(len); // Becomes "jumps/over/the/lazy/dog"

Java - split string into an array

I have this code
String speed_string = "baka baka saka laka";
String[] string_array = speed_string.split(" ");
System.out.println(string_array.length);
and it returns the value of 1 when I run it. Why is that? It seems as if only the first word of the string gets saved.
Use \\s and update the code as below
String speed_string = "baka baka saka laka";
String[] string_array = speed_string.split("\\s");
System.out.println(string_array.length);
Most probably what you think is space (ASCII decimal 32) is not (in your input string).
That would explain perfectly the behavior you're seeing.

Cannot get a Substring of a substring

I'm trying to parse a String from a file that looks something like this:
Mark Henry, Tiger Woods, James the Golfer, Bob,
3, 4, 5, 1,
1, 2, 3, 5,
6, 2, 1, 4,
For ease of use, I'd like to split off the first line of the String, because it will be the only one that cannot be converted into integer values (the rest will be stored in a double array of integers[line][value]);
I tried to use String.split("\\\n") to divide out each line into its own String, which works. However, I am unable to divide the new strings into substrings with String.split("\\,"). I am not sure what is going on:
String[] firstsplit = fileOne.split("\\\n");
System.out.println("file split into " + firstsplit.length + " parts");
for (int i = 0; i < firstsplit.length; i++){
System.out.println(firstsplit[i]); // prints values to verify it works
}
String firstLine = firstsplit[0];
String[] secondSplit = firstLine.split("\\,");
System.out.println(secondSplit[0]); // prints nothing for some reason
I've tried a variety of different things with this, and nothing seems to work (copying over to a new String is an attempt to get it to work even). Any suggestions?
EDIT: I have changed it to String.split(",") and also tried String.split(", ") but I still get nothing to print afterwards.
It occurs to me now that maybe the first location is a blank one....after testing I found this to be true and everything works for firstsplit[1];
You're trying to split \\,, which translates to the actual value \,. You want to escape only ,.
Comma , doesn't need \ before it as it isn't a special character. Try using , instead of \\,, which is translated to \, (not only a comma, also a backslash).
Not only do you not need to escape a comma, but you also don't need three backslashes for the newline character:
String[] firstSplit = fileOne.split("\n");
That will work just fine. I tested your code with the string you specified, and it actually worked just fine, and it also worked just fine splitting without the extraneous escapes...
Have you actually tested it with the String data you provided in the question, or perhaps is the actual data something else. I was worried about the carriage return (\r\n in e.g. Windows files), but that didn't matter in my test, either. If you can scrub the String data you're actually parsing, and provide a sample output of the original String (fileOne), that would help significantly.
You could just load the file into a list of lines:
fin = new FileInputStream(filename);
bin = new BufferedReader(new InputStreamReader(fin));
String line = null;
List<String> lines = new ArrayList<>();
while (( line = bin.readLine()) != null ) {
lines.add( line );
}
fin.close();
Of course you have to include this stuff into some try catch block which fits into your exception handling. Then parse the lines starting with the second one like this:
for ( int i = 1; i < lines.size(); i++ ) {
String[] values = lines.get( i ).split( "," );
}

closest thing to NSScanner in Java

I'm moving some code from objective-c to java. The project is an XML/HTML Parser. In objective c I pretty much only use the scanUpToString("mystring"); method.
I looked at the Java Scanner class, but it breaks everything into tokens. I don't want that. I just want to be able to scan up to occurrences of substrings and keep track of the scanners current location in the overall string.
Any help would be great thanks!
EDIT
to be more specific. I don't want Scanner to tokenize.
String test = "<title balh> blah <title> blah>";
Scanner feedScanner = new Scanner(test);
String title = "<title";
String a = feedScanner.next(title);
String b = feedScanner.next(title);
In the above code I'd like feedScanner.next(title); to scan up to the end of the next occurrence of "<title"
What actually happens is the first time feeScanner.next is called it works since the default delimiter is whitespace, however, the second time it is called it fails (for my purposes).
You can achieve this with String class (Java.lang.String).
First get the first index of your substring.
int first_occurence= string.indexOf(substring);
Then iterate over entire string and get the next value of substrings
int next_index=indexOf( str,fromIndex);
If you want to save the values, add them to the wrapper class and the add to a arraylist object.
This really is easier by just using String's methodsdirectly:
String test = "<title balh> blah <title> blah>";
String target = "<title";
int index = 0;
index = test.indexOf( target, index ) + target.length();
// Index is now 6 (the space b/w "<title" and "blah"
index = test.indexOf( target, index ) + target.length();
// Index is now at the ">" in "<title> blah"
Depending on what you want to actually do besides walk through the string, different approaches might be better/worse. E.g. if you want to get the blah> blah string between the <title's, a Scanner is convenient:
String test = "<title balh> blah <title> blah>";
Scanner scan = new Scanner(test);
scan.useDelimiter("<title");
String stuff = scan.next(); // gets " blah> blah ";
Maybe String.split is something for you?
s = "The almighty String is mystring is your String is our mystring-object - isn't it?";
parts = s.split ("mystring");
Result:
Array("The almighty String is ", " is your String is our ", -object - isn't it?)
You know that in between your "mystring" must be. I'm not sure for start and end, so maybe you need some s.startsWith ("mystring") / s.endsWith.

Categories