How to convert a string to character by character in Android? - android

I have Edittext field that the user can enter their name. I want to check it with alphabets for how many times a letter comes.
Which is the best way to do this?
I tried the below code for getting each character from the string but error occurring? I appreciate it if any one can help.
name=(EditText)findViewById(gami.Numerology.R.id.inputUI);
String a=name.getText().toString();
for ( int i = 0; i < a.length(); i++ )
{
c = a.charAt(i);
if (c=='s')
{
s=1; //like this for all characters
}
}
I just put this in a click event of button.

//declare the original String object
String strOrig = "Hello World";
//declare the char array
char[] stringArray;
//convert string into array using toCharArray() method of string class
stringArray = strOrig.toCharArray();
//display the array
for(int index=0; index < stringArray.length; index++)
//check of character appearance

You can use a hashmap or some sort of dictionary in Java.
Rough example since I don't know how to use Hashmap in Java:
HashMap<Character, Integer> counter = new HashMap<Character, Integer>();
for (Character c: name)
{
counter.put(c, counter.get(c) == null ? 1 : counter.get(c)++);
}

Related

How to get a random value from a string array without repetition?

How to get a random value from a string array in android without repetition?
I have array in String.xml file as below -
<string-array name="msg">
<item>Cow</item>
<item>Pig</item>
<item>Bird</item>
<item>Sheep</item>
</string-array>
I am selecting random string by using following code -
String[] array = Objects.requireNonNull(context).getResources().getStringArray(R.array.msg);
String Msg = array[new Random().nextInt(array.length)];
Can anyone help me please? Thanks is advance...!
Can you just do something like this:
Collections.shuffle(copyOfArray);
Then loop through that?
for (int i = 0; i < copyOfArray.size(); i++) {
println(copyOfArray.get(i))
}
try this -
array = Objects.requireNonNull(context).getResources().getStringArray(R.array.msg);
//String msg = array[new Random().nextInt(array.length)];
LinkedList<String> myList = new LinkedList<String>();
for (String i : array)
myList.add(i);
Collections.shuffle(myList);
for (int i = 0; i < myList.size(); i++) {
String msg=myList.get(i);
}
Try this solution,
LinkedList<String> myList = new LinkedList<String>();
String[] words = { "Cow", "Pig", "Bird", "Sheep" };
for (String i : words)
myList.add(i);
Collections.shuffle(myList);
Then,
sampleText.setText(myList.pollLast());
pollLast() in LinkedList will retrieves and removes the last element of this list, or returns null if this list is empty.
try this.
int max = array.length() - 1;
int min = 0;
String Msg = array[new Random().nextInt(max - min + 1) + min];
First convert your String resource array to ArrayList
Fill value from current ArrayList to HashSet and convert that HashSet to newly ArrayList
Now shuffle that new ArrayList

how to loop through 2d array and make the result appear in table form in android

HI below is the code which gets the four columns data from the curson and put in the 2d array. basically there are two issues one is that i get the last value as nullnullnullnull means all for columns are fetched as null.
the seconds is that i want to print the array in multitextline or if any other widget availabe so that i get four fields in a row. like
id rule_body rule_con boole
0 abc def 1
0 a f 0
c.moveToFirst();
int i=0;
while(c.moveToNext()) {
String id = c.getString(c.getColumnIndex("id"));
String rb = c.getString(c.getColumnIndex("rule_body"));
String cn = c.getString(c.getColumnIndex("rule_cons"));
String bl = c.getString(c.getColumnIndex("boole"));
table[i][0] = id;
table[i][1] = rb;
table[i][2] = cn;
table[i][3] = bl;
++i;
}
for(int a=0;a<count_row;a++)
for(int b=0;b<count_col;b++) {
obj_ml.append(String.valueOf(table[a][b]));
}
so far i am getting all the result in a single line. any help will be appreciated.
Change your for-loop as below
for (int a=0;a<count_row;a++)
{
for(int b=0;b<count_col;b++)
{
obj_ml.append(String.valueOf(table[a][b]));
}
// add to obj_ml new line character '\n'
obj_ml.append("\n");
}

How to pass edit text values to integer array in Android

I'm a beginner in Android.
I have created a edit text field where can I enter values from 0-9. Now, I have to get these values in an integer array.
example : entered values are 12345.
I need an array containing these values
int[] array = {1,2,3,4,5};
I need to know the way to do this. Kindly help.
Try this :
String str = edittext.getText.toString();
int length = str.length();
int[] arr = new int[length];
for(int i=0;i<length;i++) {
arr[i] = Character.getNumericValue(str.charAt(i));
}
You can use something like this:
int[] array = new int[yourString.length()];
for (int i = 0; i < yourString.length(); i++){
array[i] = Character.getNumericValue(yourString.charAt(i));
}

How do I grab each letter of a string in android?

I would like to create a small app, and in the app I have the user entering text in an editText. I already know the basics of editText, like how to get the text from it and enter it into a separate string variable. But after I have that string variable, how can I grab each letter of this message separately? I would assume that you need a For loop. Does anyone know of any easy way to do this?
Yes, use can use a For loop like this:
String MyEditText = myEditText.getText().toString();
int len = MyEditText.length();
char chars[] = MyEditText.toCharArray();
for(int i=0;i<len;i++){
//retrieve chars
char newChar = chars[i];
}
for (int i = 0; i < inputString.length(); i++) {
//newChar is equivalent to whatever is at position i
char newChar = inputString.charAt(i); }

How to save an array of strings with SharedPreferences?

I have an array of Strings, I need to save this array with SharedPreferences, and then read and display them on a ListView.
For now, I use this algorithm:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
//To save the strings
public void saveStrings(String[] str){
int a = 0;
int lenght = str.length;
while (a<lenght){
sp.edit().putString(Integer.toString(a), Integer.toString(str[a])).apply();
a=a+1;
}
}
//To read the strings
public String[] getStrings(){
String[] str = new String [8];
int a = 0;
int lenght = 8; //To read 8 strings
while (a<lenght){
str[a] = sp.getString(Integer.toString(a),"Null");
a=a+1;
}
return str;
}
Is there a way to save and read the entire array, rather than a string at a time?
For this project I'm using API level 19 (Android 4.4.2 KitKat)
Well, you could use putStringSet(), but (a) it's only from API level 11 onwards, and (b) as its name says, it's for sets (which means that you will lose the original ordering and any duplicates present in the array).
We solved this problem by "encoding" collections into a string and using putString() and decoding them afterwards on getString(), with this pair of methods (for ArrayList, but should be easily convertible into array versions):
public String encodeStringList(List<String> list, char separator)
{
StringBuilder sb = new StringBuilder(list.size() * 50);
for (String item : list)
{
if (sb.length() != 0)
sb.append(separator);
// Escape the separator character.
sb.append(item.replace(Character.toString(separator), "\\" + separator));
}
return sb.toString();
}
public List<String> decodeStringList(String encoded, char separator)
{
ArrayList<String> items = new ArrayList<String>();
if (encoded != null && encoded.length() != 0)
{
// Use negative look-behind with backslash, because it's used for escaping the separator.
// Expression is "(?<!\)s" with doubling because of escaping in regex, and again because of escaping in Java).
String splitter = "(?<!\\\\)" + separator; //$NON-NLS-1$
String[] parts = encoded.split(splitter);
// While converting to list, take out the escape characters used to escape the now-removed separator.
for (int i = 0; i < parts.length; i++)
items.add(parts[i].replace("\\" + separator, Character.toString(separator)));
}
return items;
}
Set<String> set =list.getStringSet("key", null);
Set<String> set = new HashSet<String>();
set.addAll(list of the string list u have);
editor.putStringSet("key", set);
editor.commit();
Please refer to this thread for further details Save ArrayList to SharedPreferences
//while storing
str is string array
String fin="";
for(i=0;i<n;i++){
fin=fin+str[i]+",";
}
fin=fin.substring(0,fin.length()-1);
//while retrieving
List<String> items = Arrays.asList(fin.split("\\s*,\\s*"));

Categories

Resources