how to shuffle a letters of array in android? - android

String arrAnimal[] = {"cat","dog","parrot","fish"};
I need to shuffle each word and set it to TextView, when click button wanna go through each element(see Shuffeled elements).

Complete working code,
String[] animals = {"cat","dog","parrot","fish"};
for (int i = 0; i < animals.length; ++i) {
List<Character> letters = new ArrayList<>(animals[i].length());
for (char c : animals[i].toCharArray()) {
letters.add(c);
}
Collections.shuffle(letters);
StringBuilder builder = new StringBuilder();
for (char c : letters) {
builder.append(c);
}
animals[i] = builder.toString();
}
System.out.println(Arrays.toString(animals));
Outputs: [tca, ogd, roptar, sifh]
EDIT: To print line by line, change the last line to,
for (String s : animals) {
System.out.println(s);
}

Use Collections.shuffle( )
ArrayList<String> list = new ArrayList<String>();
list.add("cat");
list.add("dog");
list.add("parrot");
list.add("fish");
Collections.shuffle(list);

Related

How to show list of string in TextView on Android

I want show list of strings in TextView and I get this list from server.
List from json :
"stars": [
{
"name": "Elyes Gabel"
},
{
"name": "Katharine McPhee"
},
{
"name": "Robert Patrick"
}
]
I want show this names such as this sample :
Stars = Elyes Gabel, Katharine McPhee, Robert Patrick
I should setText from this TextView in Adapter.
With below code I can show name :
model.get(position).getStars().get(0).getName();
But just show me Elyes Gabel !!!
I want show me such as this :
Stars = Elyes Gabel, Katharine McPhee, Robert Patrick
How can I it? Please help me
Here is the correct answer you might be after,
Lets just say you have the above JSON and you have converted that in a String array.
So array will look something like below:
String stars[] = {Elyes Gabel, Katharine McPhee, Robert Patrick}
TextView textView = // initialise the textview here or however you do.
StringBuilder builder = new StringBuilder();
for (String star: stars) {
builder.append(star);
builder.append(", ");
}
textView.setText(builder.toString());
You will get the desired output...
You need to loop through all "Star" elements and build the string yourself. You should have something like this:
String concatenatedStarNames = "";
List<Star> stars = model.get(position).getStars(); // I assume the return value is a list of type "Star"!
for (int i = 0; i < stars.size(); i++) {
concatenatedStarNames += stars.get(i).getName();
if (i < stars.size() - 1) concatenatedStarNames += ", ";
}
And then you set the text of the text view to concatenatedStarNames.
You can build it yourself with a StringBuilder, something like:
final Collection<Star> stars = models.get(position).getStars();
final StringBuilder builder = new StringBuilder();
boolean first = true;
for (Star star : stars) {
final String name = star.getName();
if(first) {
first = false;
builder.append(name);
} else {
builder.append(", ").append(name);
}
}
final String allStarNames = builder.toString();
you can just do - (with your same logic of accessing stars)
String strNames;
for (int i=0; i<starsCount; i++){ //starsCount = No of stars in your JSON
strNames += model.get(position).getStars().get(i).getName();
if( i != starsCount-1)
strNames += ", ";
}
textViewVariable.setText(strNames);

Handle comma separated string

Creating an app in which i want to get string from json but i have one key and multiple value so i don't know how to handle this.
"colours": "#fff600,#000000,#ffffff,#00000,#ff9900,#333333"
And want to use this color in different class:
final ValueAnimator colorAnimation = ValueAnimator.ofObject(new android.animation.ArgbEvaluator(), Color.RED, Color.BLUE,Color.WHITE,Color.YELLOW,Color.CYAN,Color.MAGENTA,Color.GREEN,Color.GRAY);
colorAnimation.setDuration(1400);
Put the value of colours in string variable and then split the string in following way and add it to an arraylist :
String[] arr = str.split(",");
ArrayList<String> arr1 = new ArrayList<String>();
for (int i=0; i<arr.length; i++){
arr1.add(arr[i]);
}
Get value of color and use string tokenizer with ',' delima like this:
StringTokenizer stringTokenizer = new StringTokenizer(colorValueString, ",");
Also it has stringTokenizer.nextToken to get the next color in string
You can get the value of colours as a string and then split the string into parts like this:
String colours = json.getString("colours");
Log.d(TAG, colours);
String items[] = colours.split(",");
for (String item : items) {
Log.d(TAG, item);
}
If you own the json
You should use JSONArray:
"colours": ["#fff600","#000000","#ffffff","#00000","#ff9900","#333333"]
And read it like
JSONObject json = ...;
JSONArray colorsArray = json.getJSONArray("colours");
for(int i = 0; i < colorsArray.length(); i++) {
String colorString = colorsArray.getString(i);
int color = Color.parseColor(colorString);
// you should probably also catch IllegalArgumentException for wrong input
}
If you don't own the json
You can read it as string and split around commas:
JSONObject json = ...;
String colorsString = json.getString("colours");
String[] colorStrings = colorsString.split(",");
for(String string : colorStrings) {
int color = Color.parseColor(string);
// you should probably also catch IllegalArgumentException for wrong input
}

Reomve special character from Arraylist

I am trying to remove special character from arraylist.
Not getting click how to do this?
I have 3 editfield and filling text after certain conditions
means when 1 is filled then another can be filled. now when i click to save this. this returns an array like [hello,abc,zbz] for fields
private List<String> hashtagData;
hashtagData = new ArrayList<String>();
String status_message = status.getText().toString();
String status_message2 = status2.getText().toString();
String status_message3 = status3.getText().toString();
hashtagData.add(status_message);
hashtagData.add(status_message2);
hashtagData.add(status_message3);
But I am trying to remove "[]".
Thank you if anybody can help.
Here try this:
ArrayList<String> strCol = new ArrayList<String>();
strCol.add("[a,b,c,d,e]");
strCol.add(".a.a.b");
strCol.add("1,2,].3]");
for (String string : strCol) {
System.out.println(removeCharacter(string));
}
private String removeCharacter(String word) {
String[] specialCharacters = { "[", "}" ,"]",",","."};
StringBuilder sb = new StringBuilder(word);
for (int i = 0;i < sb.toString().length() - 1;i++){
for (String specialChar : specialCharacters) {
if (sb.toString().contains(specialChar)) {
int index = sb.indexOf(specialChar);
sb.deleteCharAt(index);
}
}
}
return sb.toString();
}
Create regex which matches with your criteria, then loop through your list.
String myRegex = "[^a-zA-Z0-9]";
int index = 0;
for (String your_string : list)
list.set(index++, s.replaceAll(myRegex, ""));
can use below function to remove special character from string using regular expressions.
using System.Text;
using System.Text.RegularExpressions;
public string RemoveSpecialCharacters(string str)
{
return Regex.Replace(str, "[^a-zA-Z0-9_.]+", "", RegexOptions.Compiled);
}

Replacing part of String one by one

I have string:
Apple, Banana, Strawberry; Lemon, Watermelon; Orange
When I try this:
if(meaning.contains(";"))
{
meaning=meaning.replace(";", "\n");
}
Result:
Apple, Banana, Strawberry
Lemon, Watermelon
Orange
How to replace part of String one by one in order to replace ";" to "\n"+numStr?
1.Apple, Banana, Strawberry
2.Lemon, Watermelon
3.Orange
Didn't test it, but should work:
String[] lines = meaning.split(";");
StringBuilder res = new StringBuilder();
for (int i = 0, size = lines.length; i < size; i++) {
res.append(i + 1).append(". ").append(lines[i]).append("\n");
}
res.toString();
You can use the following code. The trick is to use String.split() instead of String.replace().
if(meaning.contains(";"))
{
StringBuilder builder = new StringBuilder();
String[] meanings = meaning.split(";");
for (int i = 0; i < meanings.length; i++) {
builder.append(String.format(Locale.US, "%d. %s\n", i, meanings[i].trim()));
}
Log.d("meanings", builder.toString());
}
The result will print:
1.Apple, Banana, Strawberry
2.Lemon, Watermelon
3.Orange

Converting String array to Integer Array

Since I couldn't figure out an easy way to convert my string array into an integer array, I looked up an example for a method and here is what I ended up with:
private int[] convert(String string) {
int number[] = new int[string.length()];
for (int i = 0; i < string.length(); i++) {
number[i] = Integer.parseInt(string[i]); // error here
}
return number;
}
parseInt requires a string which is what string[i] is but the error tells me "The type of the expression must be an array type but it resolved to String"
I can't figure out what is the problem with my code.
EDIT: I'm an idiot. Thanks all it was obvious.
You're trying to read a string as if it were an array. I assume you're trying to go through the string one character at a time. To do that, use .charAt()
private int[] convert(String string) {
int number[] = new int[string.length()];
for (int i = 0; i < string.length(); i++) {
number[i] = Integer.parseInt(string.charAt(i)); //Note charAt
}
return number;
}
If you expect the string to be an array of strings, however, you left out the array identifier in the function prototype. Use the following corrected version:
private int[] convert(String[] string) { //Note the [] after the String.
int number[] = new int[string.length()];
for (int i = 0; i < string.length(); i++) {
number[i] = Integer.parseInt(string[i]);
}
return number;
}
You have an error in your code. Use this code:
private int[] convert(String[] string) {
int number[] = new int[string.length];
for (int i = 0; i < string.length; i++) {
number[i] = Integer.parseInt(string[i]); // error here
}
return number;
}
Your method's parameter is a String and not a String array. You cannot access elements in a String with string[i]. If you want to actually get a single character from a String, use 'String.charAt(..)' or 'String.substring(..)'. Note that charAt(..) will return a char but those are easy enough to convert to Strings.
Use Arrays.asList( YourIntArray ) to create arraylist
Integer[] intArray = {5, 10, 15}; // cannot use int[] here
List<Integer> intList = Arrays.asList(intArray);
Alternatively, to decouple the two data structures:
List<Integer> intList = new ArrayList<Integer>(intArray.length);
for (int i=0; i<intArray.length; i++)
{
intList.add(intArray[i]);
}
Or even more:
List<Integer> intList = new ArrayList<Integer>(Arrays.asList(intArray));
.#this is worked for me

Categories

Resources