android split string doesn't work correctly [duplicate] - android

This question already has answers here:
Android split not working correctly
(2 answers)
Closed 7 years ago.
in my android app, i would like to split an array value into another array.
i have an Array with the name ArrayA.
log of ArrayA[0]:
Peter|Mustermann
now i would like to split Peter and Mustermann, i try this:
String [] ArrayB = ArrayA[0].split("|");
But the Log of ArrayB[0] and ArrayB[1] will not be:
Peter
And
Mustermann
it will be:
P
And
nothing
Any ideas ? :(

The public String[] split(String regex) works with a regular expression.
In a regular expression | is a reserved character, so try to escape it using
String [] ArrayB = ArrayA[0].split("\\|");
See here for more information about other reserved characters: http://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html#sum
And see here for a compilable sample: http://ideone.com/fjXNoJ

You'll have use it as follows:
String [] ArrayB = Array[0].trim().split("\\|");
As '\' is a special character also (along with |), two backslashes in a string literal will mean one backslash in the actual String, which in turn will represent a regular expression that matches a single backslash character.

Just use a single quote
String [] ArrayB = ArrayA[0].split('|');

Related

String.split("A;B;;;;") nor working as expected [duplicate]

This question already has answers here:
Java: String split(): I want it to include the empty strings at the end [duplicate]
(3 answers)
Closed 6 years ago.
I need split a string using ';' as separator, if the string has all of fields filled it's works good, but if some fields are not filled, like
string.split("A;B;C;;;") not work... for this string I expected that output would
[0]=A
[1]=B
[2]=C
[3]=''
[4]=''
[5]=''
, but the output is only first three fields
[0]=A
[1]=B
[3]=C
... the other fields wasn't created
Some clue how to solve this?
The ; character seperates C from the end of the string, no matter how many of them there are. The String.split() method will not return plain white space or an empty string.
If not mistaken, split looks for characters[ASCII] between the two separators and in case of
str.split("A;B;C;;;"),
there are no characters between the two semi colons. Split by defaults remove the empty string, to overrule that we need to use the overloaded split as detailed here in Java docs.
Try this if possible based on your input architecture:
String str = "A;B;C;;;";
str.split(";", -1);
This helps to look even for null string output would be
[0] = "A"
[1] = "B"
[2] = "C"
[3] = ""
[4] = ""
Hope this helps.

Converting a text file into String array with regular expression

I have a .txt file which contains above 1000 words
sample city names below
Razvilka
Moscow
Firozpur Jhirka
Kathmandu
Kiev
Pokhara
Merida
Delhi
Reshetnikovo
Ciudad Bolivar
Marfino
Zhukovskiy
Reutov
Kurovskoye
etc
I would like to have these words in this format below
"Razvilka","Moscow","etc","etc"
enclosed with double quotation and with a comma in the end.I am using Notepad++.Could you mention how to do it and which software should I use it?
If you're using Notepad++, make a Search and Replace replacing
\b(\w+)\b
with
"$1",
It'll find all words and replace with them self, surrounded by quotes. You'll have to manually remove the last , if that's unwanted.
Regards
I wonder if this question is about programming, but You tagged android, regex and android studio, so I guess it is. If yes, You can simply split a string in that way:
String[] splitted = yourString.split("\\s+");
In that case, You are splitting the strings by whitespaces (this regex is also for more than one whitespace), like Your string seems to be. If You have more than one delimiter, You can do it by using the OR operator |
String[]splitted = yourString.split("-|\\.");
In that example, You are splitting the String by - and . (minus and point). The delimiter is the sign where the String is splitted by.

trim string to a specific character

I want to trim a specific String till a specific character. So the String: com.icecoldapps.screenshoteasy for example shall be the String screenshoteasy. But larger Strings like com.google.android.syncadapters.contacts shall also be trimed to contacts.
How to do that?
Thanks
String yourString = "com.google.android.syncadapters.contacts";
String[] sArr = yourString.split("\\.");
String output = sArr[sArr.length-1];
You can use the split method to return a array with the string split into parts on a delimiter.
String whole = "com.icecoldapps.screenshoteasy"
String[] parts = whole.split('.');
So parts would be ["com" , "icecoldapps", "screenshoteasy"]
You can also split using more complicated strings of characters. Might be worth looking at Regular Expressions and the API for that.

Using a question mark as a String in android

Im trying to use a question mark as a variable for a string.
I've tried...
strings.xml
<string name="questionMark">\?</string>
.class
String questionMark;
questionMark = getResources().getString(R.string.questionMark);
String delim4 = (questionMark);
This causes a fource close regex error.
and
String delim4 = (\?);
This gets an error Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \ )
and also
I've tried putting 2 backslashes in front of it
String delim4 =(\\?)
System.out.println("delim "+ delim4);
But that just escapes the second slash and sometimes force closes as well.
the output for that was
delim \?
Can any tell me how to put in the question mark as the string. I'm using it as variable to spit a string. The String Im splitting can not be changed.
plz help
Edit added split code
if (FinishedUrl.contains(questionMark)){
String delim3 = (".com/");
String[] parts3 = FinishedUrl.split(delim3);
String JUNK3= parts3[0];
String fIdStpOne = parts3[1];
String fIdStpTwo = fIdStpOne.replaceAll("=#!/","");
String delim4 = (questionMark);
String[] parts4 = fIdStpTwo.split(delim4);
String fIdStpThree= parts3[0];
String JUNK4 = parts3[1];
FId = fIdStpThree;
}
As pointed out by user laalto, ? is a meta-character in regex. You must work around that.
Let's see what's happening here. Firstly, some ground rules:
`?` is not a special character in Java
`?` is a reserved character in regex
This entails:
String test = "?"; // Valid statement in java, but illegal when used as a regex
String test = "\?"; // Illegal use of escape character
Why is the second statement wrong? Because we are trying to escape a character that isn't special (in Java). Okay, we'll get back to this.
Now, for the split(String) method, we need to escape the ? - it being a meta-character in regex. So, we need \? for the regex.
Coming back to the string, how do we get \?? We need to escape the \(backslash) - not the question mark!
Here's the workflow:
String delim4 = "\\?";
This statement gives us \? - it escapes the \(backslash).
String[] parts4 = fIdStpTwo.split(delim4);
This lets us use \? as a regex in the split() method. Since delim4 is being passed as a regex, \? is used as ?. Here, the prefix \ is used to escape ?.
Your observations:
String delim4 = (\?);
This gets an error Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \ )
I covered this above. You are escaping ? at the java level - but it isn't a special character and needs no escaping - hence the error.
String delim4 =(\\?)
System.out.println("delim "+ delim4);
But that just escapes the second slash and sometimes force closes as well. the output for that was
delim \?
This is what we want. It is easier to think of this as a two stage process. The first stage deals with successfully placing a \(backslash) in front of the ?. In the second stage, regex finds that the ? has been prefixed by a \ and uses ? as a literal instead of a meta-character.
And here's how you can place the regex in your res/values/strings.xml:
<string name="questionMark">\\?</string>
By the way, there's another option - not something I use on a regular basis these days - split() works just fine.
You can use StringTokenizer which works with delimiters instead of regex. Afaik, any literal can be used as a delimiter. So, you can use ? directly:
StringTokenizer st = new StringTokenizer(stringToSplit, "?");
while (st.hasMoreTokens()) {
// Use tokens
String token = st.nextToken();
}
Easiest way is to quote or backslash them:
<string name="random">"?"</string>
<string name="random">\?</string>
The final code.
String startDelim = ("\\?");
String realDelim = (startDelim);
String[] parts4 = fIdStpOne.split(realDelim);
String fIdStpTwo= parts4[0];
String JUNK4 = parts4[1];
Normally you'd just put it literally, like
String q = "?";
However, you say you're using it to split a string. split() takes a regular expression and ? is a metacharacter in a regex. To escape it, add a backslash in front. Backslash is a special character in Java string literals so it needs to be escaped, too:
String q = "\\?";

android java URLDecoder problem

i have a String displayed on a WebView as "Siwy & Para Wino"
i fetch it from url , i got a string "Siwy%2B%2526%2BPara%2BWino". // be corrected
now i'm trying to use URLDecoder to solve this problem :
String decoded_result = URLDecoder.decode(url); // the url is "Siwy+%26+Para+Wino"
then i print it out , i still saw "Siwy+%26+Para+Wino"
Could anyone tell me why?
From the documentation (of URLDecoder):
This class is used to decode a string which is encoded in the application/x-www-form-urlencoded MIME content type.
We can look at the specification to see what a form-urlencoded MIME type is:
The form field names and values are escaped: space characters are replaced by '+', and then reserved characters are escaped as per [URL]; that is, non-alphanumeric characters are replaced by '%HH', a percent sign and two hexadecimal digits representing the ASCII code of the character. Line breaks, as in multi-line text field values, are represented as CR LF pairs, i.e. '%0D%0A'.
Since the specification calls for a percent sign followed by two hexadecimal digits for the ASCII code, the first time you call the decode(String s) method, it converts those into single characters, leaving the two additional characters 26 intact. The value %25 translates to % so the result after the first decoding is %26. Running decode one more time simply translates %26 back into &.
String decoded_result = URLDecoder.decode(URLDecoder.decode(url));
You can also use the Uri class if you have UTF-8-encoded strings:
Decodes '%'-escaped octets in the given string using the UTF-8 scheme.
Then use:
String decoded_result = Uri.decode(Uri.decode(url));
thanks for all answers , i solved it finally......
solution:
after i used URLDecoder.decode twice (oh my god) , i got what i want.
String temp = URLDecoder.decode( url); // url = "Siwy%2B%2526%2BPara%2BWino"
String result = URLDecoder.decode( temp ); // temp = "Siwy+%26+Para+Wino"
// result = "Swy & Para Wino". !!! oh good job.
but i still don't know why.. could someone tell me?

Categories

Resources