Android String Array Manipulation - android

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).

Related

How do I read only a specific part of the string in Android Studio?

If a send a string in the following format: 1234,1234,1234,1234; from Arduino to Android Studio (java (intelliJ)) based. with the amount of characters between every komma changing. How do i make it so that my code only reads the string from for example 0 to the , Or from the first , to the second ,?
If you are using Java, I would recommend looking into the Java.String.split() method. This method will split your string in an array of strings, depending on your delimiter. For example :
String s = "1234,1234,1234,1234";
String[] result = s.split(",");
You can split the input string based on any special character,in your case ,, as follows
String inputString = "1234,1234,1234,1234";
String[] separated = inputString.split(",");
Log.i("MainActivity",separated[0]) // prints the first string which is 1234
// to loop over all strings
for(String s : separated){
Log.i("MainActivity",s)
}

How can i get few characters from String?

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);

Convert String to Character Array? and Retrieve

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]);

Can you call a string resource with a string?

I have a method that returns one of about 20 possible strings from an EditText. Each of these strings has a corresponding response to be printed in a TextView from strings.xml. Is there a way to call a string from strings.xml using something like context.getResources().getString(R.strings."stringFromMethod")? Is there another way to call a string from a large list like that?
The only methods I can think of is converting each string to an int, and use that to find a string in a string array, or a switch statement. Both of which involve a huge amount if-else if statements to convert the string to an int, and would take just enough steps to change if any strings were added or taken away that I'd be more likely to miss one and have fun bug hunting. Any ideas to do this cleanly?
Edit: Forgot to add, another method I tried was using was to get the resourceID from
int ID = context.getResources().getIdentifier("stringFromMethod", "String", context.getPackageName())
and taking that integer and putting it in
context.getResources().getString(ID)
That doesn't appear to be working either.
No, you can't. The getString() requires the resource id in integer format, so you can't append a string to it.
You can, however, try this:
String packageName = context.getPackageName();
int resId = context.getResources().getIdentifier("stringFromMethod", "string", packageName);
if (resId == 0) {
throw new IllegalException("Unknown string resource!"; // can't find the string resource!
}
string stringVal = context.getString(resId);
The above statements will return string value of resource R.string.stringFromMethod.
You need to use reflection (pretty ugly but only solution) load the R class, and get the relevant field by you string and get the value of it.
this is what I used to do in these kind of situations, I will made a Array like
int[] stringIds = { R.string.firstCase,
R.string.secondCase, R.string.thridCase,
R.string.fourthCase,... };
int caseFromServer=getCaseofServerResponse();
here caseFromServer varies from 0 to wahtever
and then simply
context.getResources().getString(stringIds[caseFromServer]);

Extracting only a specified part of a string in Android

Let's say I have a string :
{"id":"123","xCoord":"01.234567","yCoord":"89.012345","etc.":"etcetc"}
I want to extract only the xCoord part - the number 01.234567 and put it into a string array String[] xCoords = {};
I cannot use the public String substring (int start, int end) function because in future the id will eventually grow up and I don't have a firm index to use.
What would you suggest me - is there any way of extracting only the symbols after "xCoord":" and before ","y...
The best (and most reliable) option would be to convert your string (which is valid JSON) into an object and reference it that way.
Convert JSON String to Java Object or HashMap

Categories

Resources