How to combine loop result in dart - android

Hello i have a simple for loop what i want to combine the loop results into 1 string separated with a comma
String loc;
for(var q=0; q<2; q++){
userData = res;
loc = userData[q]['location'];
print(loc); //value in first loop is location A value in first second loop is location B i want to combine them on 1 string
}

If you want just append in String then
void main() {
String loc="";
List<String> locs = ["a","d","B","C"];
for(var q=0; q<2; q++){
loc = (loc.length>0? (loc+", ") : loc)+ (locs[q] ?? " ");
}
print(loc);
}

The traditional way would be to collect the strings into a string buffer, and manually add the comma:
var buffer = StringBuffer();
String separator = ""; // Avoid leading comma.
for (var data in userData) {
buffer..write(separator)..write(data["location"]);
separator = ",";
}
var loc = buffer.toString();
Another approach is to collect the values into a list and then use the join method:
var loc = [for (var data in userData) data["location"]].join(",");
That's probably more convenient in most cases, except when you need to do fancy computation on each element.
I have avoided using the for(;;) loop since you don't actually use the index for anything except accessing the user data. Then it's better to just for/in over the list elements directly.

Try ForEach
void main() {
List<String> places = ['New York', 'London', 'Berlin'];
String linearPlace = '';
places.forEach((thePlace) {
linearPlace = linearPlace + thePlace + ", ";
});
print(linearPlace);
//output: New York, London, Berlin,
// In case of Map
Map<String, String> countryCapitalsMap = {'Austria': 'Vienna',
'Armenia': 'Yerevan', 'India': 'Delhi'};
String countryWithCap = '';
countryCapitalsMap.forEach((key, value) {
countryWithCap = countryWithCap + key + ': ' + value + "\n";
});
print(countryWithCap);
// output:
// Austria: Vienna
// Armenia: Yerevan
// India: Delhi
}

Related

how to get the indexes of all the occurences of words in string?

I want to get indexes of all the occurences of string_to_be_search
Input:
String line="hello this is prajakta , how are you?? hello this is prajakta!"
String text_to_search= "hello this is prajakta"
Here the occurrences of text_to_search is 2 so I need list of starting indexes
Output:
List l=[0,39]
Also I have tried a code below
public List getIndexesOfMultipleOccuredString(String originalString,String textToSearch) {
int i, last = 0, count = 0;
List l = new ArrayList();
do {
i = originalString.indexOf(textToSearch, last);
if (i != -1) l.add(i);
last = i + textToSearch.length();
} while (i != -1);
return l;
}
BUT
if my input is as follows
String line="hello this is prajakta ,i love to drive car and i am a carpainter"
String text_to_search="car"
Output:
It gives me two indexes as carpainter contains car which i don't want
Output should be [39]
This is how you do it using regex(word matching)
String line= "hello this is prajakta , how are you?? hello this is prajakta!";
String text_to_search = "\\bhello this is prajakta\\b";
ArrayList<Integer> list = new ArrayList<>();
Pattern p = Pattern.compile(text_to_search);
Matcher m = p.matcher(line);
while (m.find()) {
list.add(m.start());
}
Log.i("All occurrences", "values are " + list.toString());
Output: [0, 39]
If you search using these strings
String line="hello this is prajakta ,i love to drive car and i am a carpainter";
String text_to_search="car";// use as "\\bcar\\b"
Output [40]

ReplaceAll not working

I'm using google volley to retrieve source code from website. Some looping was done to capture the value in the code. I've successfully captured the data I wanted, but error was shown: NumberFormatException: Invalid float: "2,459.00"
My intention was to store the value after the class=ListPrice>
Sample:
RM 2,899.00
The example value of the source code I wanted to save is "RM2,459.00 "
Below is the code I've written:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lazada_result);
lelongResult = (TextView) findViewById(R.id.lelong_result);
RequestQueue lelong = MyVolley.getRequestQueue(this);
StringRequest myLel = new StringRequest(
Method.GET,
"http://list.lelong.com.my/Auc/List/List.asp?DA=A&TheKeyword=iphone&x=0&y=0&CategoryID=&PriceLBound=&PriceUBound=",
RetrieveLelong(), createMyReqErrorListener());
lelong.add(myLel);
}
private Response.Listener<String> RetrieveLelong() {
return new Response.Listener<String>() {
#Override
public void onResponse(String response) {
ArrayList<Float> integers = new ArrayList<>();
String to = "class=ListPrice>";
String remainingText = response;
String showP = "";
while (remainingText.indexOf(to) >= 0) {
String tokenString = remainingText.substring(remainingText
.indexOf(to) + to.length());
String priceString = tokenString.substring(0,
tokenString.indexOf("<"));
float price = Float.parseFloat(priceString.replaceAll("[^\\d,]+", "").trim());
integers.add((price / 100));
remainingText = tokenString;
}
for (int i = 0; i < integers.size(); i++) {
String test1 = Float.toString(integers.get(i));
showP += test1 + "\n";
}
lelongResult.setText(showP);
}
};
}
The problem was as below:
I've tried all sort of replaceAll(),
1)replaceAll("[^\d,]+","") result:2,89900
replace all character except digits and comma works.
2)replaceAll("[^\d]+","") result:Invalid int""
replace all character include comma and dot ,not working
3)replaceAll("[^\d.]+,"") result:Invalid int""
replace all character exclude digits and dot, not working
From the experiment 2&3 coding above,I've noticed that if the comma were removed,i cant parseFloat as the value received by it is: "".NumberFormatException:Invalid Float:"" shown.
From the experiment 1,NumberFormatException:Invalid Float "2,45900" is showned.
The problem was replacing comma ,the code will not work but with the presence of comma ,the value cannot be stored into string
try this:
float price = Float.parseFloat(priceString.replaceAll("RM", "").trim());
use `replaceAll(Pattern.quote(","), "");
EDIT
if you want only numbers then use this
String s1= s.replaceAll("\D+","");
Try to parse the number by specifying the Locale.
NumberFormat format = NumberFormat.getInstance(Locale.KOREAN);
Number number = format.parse(priceString.replaceAll("RM", ""));
double d = number.doubleValue();
I'm just guessing the locale, don't know what you should use, depends on country
You need to do it one by one
priceString=priceString.replaceAll("\\D", "");
priceString=priceString.replaceAll("\\s", "");
now
priceString=priceString.trim();
float price = Float.parseFloat(priceString);
the problem is that in your code:
priceString.replaceAll(Pattern.quote(","), "");
float price = Float.parseFloat(priceString.replaceAll("\\D+\\s+", "").trim());
You are replacing coma but not storing the value!
you have to do:
priceString = priceString.replaceAll(",", "");
float price = Float.parseFloat(priceString.replaceAll("\\D+\\s+", "").trim());
I'm not sure of the pattern "\D+\s" because if you remove the coma you don't need to replace anything else (except "RM" that i assume you already removed)
Update: set locale and parse a number:
NumberFormat format = NumberFormat.getInstance(Locale.KOREAN);
Number number = format.parse(priceString.replaceAll("RM", ""));
double d = number.doubleValue();

add double quotes in string using android

I have string in forloop, I want add that in to another string like the given format
for (int i = 0; i < profiles.length(); i++) {
JSONObject c = profiles.getJSONObject(i);
String admnno = c.getString(TAG_ADMNNO);
}
The result should be like this
"Rajesh", "Mahesh", "Vijayakumar"
or
final CharSequence[] items = {"Rajesh", "Mahesh", "Vijayakumar"};
The adminno should be in double quotes and following comma. Its in android doin Background()
Use \" for this
For example String str="\"Rajesh\""
Try this,
if (TextUtils.isEmpty(string))
return "";
final int lastPos = string.length() - 1;
if (lastPos < 0 || (string.charAt(0) == '"' && string.charAt(lastPos) == '"'))
return string;
return "\"" + string + "\"";
Another option is to use Kotlin's multiline strings. Especially useful when you need hardcode big JSON for UTests:
val jsonString = """
{
"string_key": "value",
"boolean_key": true
}
"""
You can also try this
var id = "\"id\": \""
Output = "id": "
You have to escape the quote using \" like below:
public static String getQuotedString(String sample){
return "\"".concat(sample).concat("\"");
}
In Kotlin, you can use a variable value like this way
val searchText = "Android"
textview.text = "5 articles found for \"$searchText\""
For fixed string:
String str="5 articles found for \"IOS\" "
value is equal for
5 articles found for "IOS"

Deleting a word in a String/String Array

So if you are adding in a string, you can just add them via += method(the one i know and using atm). but how can you delete a word in a string/string array?
example: i have a string
String="Monday,Tuesday,Wednesday"
how do you make it into
String="Monday,Wednesday"
any help please?
You could use the replace method.
String sentence = "Monday,Tuesday,Wednesday";
String replaced = sentence.replace("Tuesday,", "");
its easy
just use
yourString = yourString.replaceAll("the text to replace", ""); //the second "" show empty string so the text will get replace by empty string
finally yourString will contain the text u desire Thats it :)
You can use the "public String replace(char oldChar, char newChar)" method if you want to remove "Tuesday" and not the second element
https://stackoverflow.com/questions/16702357/how-to-replace-a-substring-of-a-string
I think, i will use it for simplicity otherwise go to other suggested answer...
Use Arraylist for storing days:
ArrayList<String> days = new ArrayList<String>();
days.add("Monday");
days.add("Tuesday");
days.add("Wednesday");
Use it for creating days string:
public String getDays() {
String daysString = "";
for (int i = 0; i < days.size(); i++) {
if (i != 0)
daysString += ", ";
daysString += days.get(i);
}
return daysString;
}
And whenever you want to remove use
days.remove(1);
or
days.remove("Tuesday");
then again call getDays();
IInd Method if you want to use only string:
String list = "Monday,Tuesday,Wednesday";
System.out.println("New String : " + removeAtIndex(list, 1));
and
public String removeAtIndex(String string, int index) {
int currentPointer = 0;
int lastPointer = string.indexOf(",");
while (index != 0) {
currentPointer = string.indexOf(',', currentPointer) + 1;
lastPointer = string.indexOf(',', lastPointer + 1);
index--;
}
String subString = string.substring(currentPointer,
lastPointer == -1 ? string.length() : lastPointer);
return string.replace((currentPointer != 0 ? "," : "") + subString
+ (currentPointer == 0 ? "," : ""), "");
}
Something like this using a regular expression:
String contents = "Monday,Tuesday,Wednesday";
contents = contents.replaceAll("[\\,]+Tuesday|^Tuesday[\\,]*", "");

How can I effectively replace one or more characters

I have a String separated by commas as follows
1,2,4,6,8,11,14,15,16,17,18
This string is generated upon user input. Suppose the user wants to remove any of the numbers, I have to rebuild the string without the specified number.
If the current string is:
1,2,4,6,8,11,14,15,16,17,18
User intents to remove 1, the final string has to be:
2,4,6,8,11,14,15,16,17,18
I tried to achieve this using the following code:
//String num will be the number to be removed
old = tv.getText().toString(); //old string
newString = old.replace(num+",",""); //will be the new string
This might be working sometimes but it is sure that it won't work for the above example I have shown, if I try to remove the 1, it also removes the last part of 11, because there also exists 1.
well you can use this. Its the most simplest approach i can think of:
//String num will be the number to be removed
old=","+tv.getText().toString()+",";//old string commas added to remove trailing entries
newString=old.replace(","+num+",",",");// will be the new string
newString=newString.substring(1,newString.length()-1); // removing the extra commas added
This would work for what you want to do. I have added a comma at the start and end of your string so that you can also remove the first and last entries too.
You can split the string first and check for the number where you append those value that is not equivalent to the number that will get deleted;
sample:
String formated = "1,2,4,6,8,11,14,15,16,17,18";
String []s = formated.split(",");
StringBuilder newS = new StringBuilder();
for(String s2 : s)
{
if(!s2.equals("1"))
newS.append(s2 + ",");
}
if(newS.length() >= 1)
newS.deleteCharAt(newS.length() - 1);
System.out.println(newS);
result:
2,4,6,8,11,14,15,16,17,18
static public String removeItemFromCommaDelimitedString(String str, String item)
{
StringBuilder builder = new StringBuilder();
int count = 0;
String [] splits = str.split(",");
for (String s : splits)
{
if (item.equals(s) == false)
{
if (count != 0)
{
builder.append(',');
}
builder.append(s);
count++;
}
}
return builder.toString();
}
String old = "1,2,4,6,8,11,14,15,16,17,18";
int num = 11;
String toRemove = "," + num + "," ;
String oldString = "," + old + ",";
int index = oldString.indexOf(toRemove);
System.out.println(index);
String newString = null;
if(index > old.length() - toRemove.length() + 1){
newString = old.substring(0, index - 1);
}else{
newString = old.substring(0, index) + old.substring(index + toRemove.length() -1 , old.length());
}
System.out.println(newString);

Categories

Resources