trim string to a specific character - android

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.

Related

android: divide string with punctuation and maintain punctuation with sentence in array

I have a sentence,
hello, What you are doing?How are you?
I wanted to split the sentence with characters such as .,?
I have achieved it using split function
and the output is:
arr[0]=hello
arr[1]=What you are doing
arr[2]=How are you
but I want the array as
arr[0]=hello
arr[1]=,
arr[2]=What you are doing
arr[3]=?
arr[4]=How are you
arr[5]=?
I have done this code
String text = "hello, What you are doing?How are you?";
String[] arr= text.split("[\\.,!;?:\"]+");
for (String str : arr) {
System.out.println(str);
}
Please help.
The general strategy to preserve text while also splitting on it at the same time is to use lookarounds. Lookarounds assert logic, but do not actually consume any text. They are basically zero width. I split below using the pattern:
(?=[\\.,!;?:\"])|(?<=[\\.,!;?:\"])
This says to split if we lookahead or lookbehind and see a punctuation character.
String sentence = "hello, What you are doing?How are you?";
String[] parts = sentence.split("(?=[\\.,!;?:\"])|(?<=[\\.,!;?:\"])");
for (String part : parts) {
System.out.println(part);
}
hello
,
What you are doing
?
How are you
?
Demo
You might also want to run String#trim on each term to get the exact output you want.

is it possible to cut text from string like this?

I want to put extra value from intent to other intent. But in other intent, app get all value. Example:
mAddress.setText(" from " + address);
String put_address = mAddress.getText().toString();
editIntent.putExtra("put_address", put_address);
is it possible to cut text "from" and get only address variable ???
you can split a string like
str = "From address#dd.com";
String modified = str.replace;
now splitstr contain your split strings
splitStr[1] contains "address#dd.com"
Can also use
str.substring(str.indexOf(" ")+1);
By the way, you can use jagapathi's answer. In his example he uses regular expression.
Regular expressions can help to parse, find, cut substrings using a particular pattern. In his code he splits string by any space character.
But, imho, the simplest solution is to create a substring using this code:
'put_address.substring(7);'
use one of these solutions:
String input = put_address.trim().substring(5);
*** note: 5 is index of real address first character;
String input = put_address..split(" ")[1];

why #character is missing while i split string using comma(,) in andorid?

1.here i want same string as on xml format but while i store into array it missed # from the string and added space
<string xmlns="http://tempuri.org/">7633,abcd#123</string>
loginDetailsArray = loginDetails.split(",");
intPersonID = loginDetailsArray[0];
strPassword = loginDetailsArray[1];
separeted using comma
resultstring=abcd 123//# is missing
You can try to replace # or any special characters with equivalent sign;
However you may not change password charactres.
Your SMS API might be not allowing passing Special characters.
You does not encode character '#'. Encode it ->
#amp;

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 = "\\?";

How to get tags from textfield?

I have a textfield in android called TagField.
I have an array of Strings called ListOfTags.
I enter a few words separated by spaces into Tagfield and require the function to extract the tags and store it into ListOfTags.
The algorithm I have in mind is:-
Store the string from the field into a String object
To first locate positions of all the spaces and store it in an array
Use the positions to extract sub strings from the main string
Store each sub string into ListOFStrings
My Question is, Is there a more efficient method?
Since I am using a lot of arrays
This can be achieved as-
String str = tagField.getText().toString();//get string from the editText.
String[] strArray = str.split(" ");//regular expression which separates the tags.
List<String> listOfTags = Arrays.asList(strArray);
Hope this helps.

Categories

Resources