I have one String and into this string I have a url between two characters # such as "Hello world #http://thisurl# my name is Pippo" I want to take the url (http://thisurl) between two #.
How can I do ? Thanks
String data[] = str.split("#"); //spilliting string and taking into array
ArrayList<String> urlList = new ArrayList<String>();
for (int i = 0; i < data.length; i++) {
if(data[i].contains("http://"))
urlList.add(data[i]); //if string contains "http://" it means it is url save int list.
}
now you can get all uls from urlList.get(i) method.
this urlList will give you all the urls available in the string. I dint applied any null or other check. Apply it and try. If want something else try modifying content and checks.
Try String.split(). You really should be trying to google these things first.
here is an example - http://www.java-examples.com/java-string-split-example
The split method divides a string into several strings and store them into an array using a delimiter which can be defined by you.
the second element in the resulting array will be your URL
Related
I have an string
String name = "\"edge_followed_by\":{\"count\":46199005},\"followed_by_viewer\":false,"
I want only this 46199005.
But { shows an error, when try to split the string
String[] separated = name.split("edge_followed_by\":{\"count\":");
Showing a suggestion , number expected and want me to replace with *.
Can anyone help me in this.
Just replace { with \{.
split is trying to use it as a part of regular expression.
Ideally, you should use JSON to parse this if you have proper structure. but if you want to get only the number you can split it using ":" and then split using "}". it should give you the exact number.
Why not to use:
String[] separated = name.split(":");
separated[2].split("}")[0];
Your string is not exact JSON object otherwise you can simply do json parsing and get the count value.
You can get count value using subtring operations like below:
String name = "\"edge_followed_by\":{\"count\":46199005},\"followed_by_viewer\":false,";
String substr = name.substring(name.indexOf("\"count\":") + 10);
String finalstr = substr.substring( 0, substr.indexOf("},"));
Log.d("Extracted_Value", finalstr); // output -> 46199005
There can be multiple ways. This is just one. Hope it will help you!
In my Application i am saving Contacts in SharedPreferences but the array which i am passing is also including open braces and double Quotes in the string.
like this ["contactnumber1","contactnumber2","contactnumber3".......]
but i need the string to be like this
contactnumber1,contactnumber2,contactnumber3....
so that i can use this contactnumbers string to directly place it in sms app and send alert msg with click of a button.
please help me with this
Code:
String[] arrayOfString=localMultiAutoCompleteTextview.getText().toString().split(",");
// Create a JSONArray to store all numbers
JSONArray numberArray=new JSONArray();
// Loop through the multiautocomplete textview value array
for(int i=0; i < arrayOfString.length; i++)
{
// Check whether the string contains '%'
if(arrayOfString[i].contains("%"))
{
// Add numbers to the array
numberArray.put(arrayOfString[i].split("%")[1]);
}
}
// Store the complete number array in preference as String
sp=getActivity().getSharedPreferences("sdat", 2);
ed=sp.edit();
ed.putString("snum", numberArray.toString());
ed.commit();
// To read the numbers after saving
String display = sp.getString("snum", new JSONArray().toString());
System.out.println(display);
Toast.makeText(getActivity(),"Contacts Saved:"+display,Toast.LENGTH_SHORT ).show();
}
});
The following line is a regex which matches quotes and brackets, and removes them from the string. Just call replaceAll and it will go through your string, find the following characters: '[', ']', '"' and remove them from the string.
strWithoutQuotesAndBraces = strWithQuotesAndBraces.replaceAll("(["[\\]])", "");
I want to retrieve few characters from string i.e., String data on the basis of first colon (:) used in string . The String data possibilities are,
String data = "smsto:....."
String data = "MECARD:....."
String data = "geo:....."
String data = "tel:....."
String data = "MATMSG:....."
I want to make a generic String lets say,
String type = "characters up to first colon"
So i do not have to create String type for every possibility and i can call intents according to the type
It looks like you want the scheme of a uri. You can use Uri.parse(data).getScheme(). This will return smsto, MECARD, geo, tel etc...
Check out the Developers site: http://developer.android.com/reference/android/net/Uri.html#getScheme()
Note: #Alessandro's method is probably more efficient. I just got that one off the top of my head.
You can use this to get characters up to first ':':
String[] parts = data.split(":");
String beforeColon = parts[0];
// do whatever with beforeColon
But I don't see what your purpose is, which would help giving you a better solution.
You should use the method indexOf - with that you can get the index of a certain char. Then you retrieve the substring starting from that index. For example:
int index = string.indexOf(':');
String substring = string.substring(index + 1);
How do I create a character array from a string? for example, say I have the string "Hello World"
How would I convert it to a character array?
Once converted, how do I retrieve each individual letter one by one?
My code:
public Character[] toCharacterArray(String s) {
if (s == null) {
return null;
}
Character[] array = new Character[s.length()];
for (int i = 0; i < s.length(); i++) {
array[i] = new Character(s.charAt(i));
}
return array;
}
Now if the above was implemented, how would I retrieve the returned character and how would I output it in an edit text box? using outputBox.setText(); maybe?
you can convert a String to Char array simply using toCharArray() method...
char[] charArray = string.toCharArray();
So, your updated method should be as follows...
public char[] toCharacterArray(String s) {
char[] array = s.toCharArray();
return array;
}
This appears to be a homework question, so I'm only going to give hints.
1) How would I convert it to a charterer array?
You've already done that!! However:
it would possibly be better if either you used a char[] instead of a Character[], and
if you do continue to use a Character, then it is better to use Character.valueOf(...) instead of new Character(...).
2) once converted how do I retrieve each and individual letter 1 by 1?
Use a for loop. It is one of the standard Java statements. Refer to your Java textbook, tutorial, lecture notes ...
... how would i output it in an edit text box... using outputbox.setText(????)
Use static Character.toString(char), or Character.toString() to create a String, depending on the type you have used. You can then pass that as an argument to setText ...
For details of the methods I mentioned above, read the javadocs.
Convert the string to a simple char array like this:
String test = "hello";
char[] chars = test.toCharArray();
Then you can output any particular char in the array like this:
outputbox.setText(String.valueOf(chars[i]);
I have a lengthy string in my Android program.
What I need is, I need to split each word of that string and copy that each word to a new String Array.
For eg: If the string is "I did android program" and the string array is named my_array then each index should contain values like:
my_array[0] = I
my_array[1] = did
my_array[2] = Android
my_array[3] = Program
A part of program which I did looks like this:
StringTokenizer st = new StringTokenizer(result,"|");
Toast.makeText(appointment.this, st.nextToken(), Toast.LENGTH_SHORT).show();
while(st.hasMoreTokens())
{
String n = (String)st.nextToken();
services1[i] = n;
Toast.makeText(appointment.this, st.nextToken(), Toast.LENGTH_SHORT).show();
}
Can any one please suggest some ideas..
Why not use String.split() ?
You can simply do
String[] my_array = myStr.split("\\s+");
Since '|' is a special character in regular expression, we need to escape it.
for(String token : result.split("\\|"))
{
Toast.makeText(appointment.this, token, Toast.LENGTH_SHORT).show();
}
You can use String.split or Android's TextUtils.split if you need to return [] when the string to split is empty.
From the StringTokenizer API docs:
StringTokenizer is a legacy class that
is retained for compatibility reasons
although its use is discouraged in new
code. It is recommended that anyone
seeking this functionality use the
split method of String or the
java.util.regex package instead.
Since String is a final class, it is by default immutable, which means you cannot make changes to your strings. If you try, a new object will be created, not the same object modified. Therefore if you know in advance that you are going to need to manipulate a String, it is wise to start with a StringBuilder class. There is also StringBuffer for handling threads. Within StringBuilder there are methods like substring():
substring(int start)
Returns a new String that contains a subsequence of characters currently contained in this character sequence.
or getChars():
getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Characters are copied from this sequence into the destination character array dst.
or delete():
delete(int start, int end)
Removes the characters in a substring of this sequence.
Then if you really need it to be a String in the end, use the String constructor(s)
String(StringBuilder builder)
Allocates a new string that contains the sequence of characters currently contained in the string builder argument.
or
String(StringBuffer buffer)
Allocates a new string that contains the sequence of characters currently contained in the string buffer argument.
Although to understand when to use String methods and when to use StringBuilder, this link or this might help. (StringBuilder comes in handy with saving on memory).