How do I get the first character of a string in dart flutter.
For example,a string having a value "Hello World" should return only "H".
I am fetching data from my firestore database.
My code is:
searchByName(String searchField) {
return Firestore.instance
.collection('posts')
.where('description',
isEqualTo: searchField.substring(0, 1).toUpperCase())
.getDocuments();
}
I want to get the first letter from the data that I recieve from 'description' field in above code.
You can do this by getting the first element of the String (indicated by index 0):
'${mystring[0]}'
example:
String mystring = 'Hello World';
print('${mystring[0]}');
in this case you will get as an output:
H
To get first character of string you should use method substring
Example:
word.substring(0,1);
For Perform Searching in Firebase Document Field This Will Work
void main() {
String mystring = 'Hello World';
String search = '';
for (int i=0;i<mystring.length;i++){
search += mystring[i];
print(search);
}
}
Output
H
He
Hel
Hell
Hello
Hello
Hello W
Hello Wo
Hello Wor
Hello Worl
Hello World
For me this Works.
Needed to get first n values rather than just one, and kept getting Value not in range: 10 error using substring, here's a helper function to cut a string down to the first x characters:
//* Limits given string, adds '..' if necessary
static String shortenName(String nameRaw, {int nameLimit = 10, bool addDots = false}) {
//* Limiting val should not be gt input length (.substring range issue)
final max = nameLimit < nameRaw.length ? nameLimit : nameRaw.length;
//* Get short name
final name = nameRaw.substring(0, max);
//* Return with '..' if input string was sliced
if (addDots && nameRaw.length > max) return name + '..';
return name;
}
Usage:
return Helpers.shortenName('Sausage', nameLimit: 5);
Related
iam using a package called "react-native-phone-number-input" for phoneInput, package
here iam able to formate the phone number according to the phone number length but iam not able to
formate it onchanging the text.
i have tried assigning the onchangeText value to the value prop of phone input but it didn't worked as like other TextInput components
function formatPhoneNumber(value) {
if (!value) return value;
const phoneNumber = value.replace(/[^\d]/g, '');
const phoneNumberLength = phoneNumber.length;
if (phoneNumberLength < 4) return phoneNumber;
if (phoneNumberLength < 7) {
return `(${phoneNumber.slice(0, 3)}) ${phoneNumber.slice(3)}`;
}
return `(${phoneNumber.slice(0, 3)}) ${phoneNumber.slice(
3,
6
)}-${phoneNumber.slice(6, 9)}`;
}
i have used this function for formating
String servicePrice = serviceListArrayList.get(position).getPrice();
System.out.println ("Price======>"+servicePrice);
price = Integer.parseInt(servicePrice);
System.out.println("IntPrice====>"+price);
I want to convert this servicePrice value to integer value but unfortunately got NumberFormatException,please help me from this error.
You will get a NumberFormatException if servicePrice is not a string representation of an integer (e.g. "1" or "123"). Examples include an empty string (""), text ("abc"), decimal numbers ("1.23"), currencies ("$1.23" or "$2"), or things that aren't valid numbers ("1.2.3" or "0..1")
If you aren't in control of the string, you'll want to use appropriate checks to handle if a bad value is entered
int val = 0;
try {
val = Integer.parseInt(str);
}
catch(NumberFormatException np) {
// handle the case - e.g. error Toast message
}
The exception NumberFormatException is just only because the servicePrice value is not the number String. ( Any string value which is not convertible to as number value)
Better you catch the, price = Integer.parseInt(servicePrice);
For example
try
{
price = Integer.parseInt(servicePrice);
}
catch(NumberFormatException ex)
{ // you can assign default as 0 here too.
price =0;
}
int price = Integer.parseInt(serviceprice)
Log what value is stored in serviceprice
You can only convert numbers to String not alphabets.
Your serviceListArrayList.get(position).getPrice() might be returning some price with alphabets such as rs or dollars.
So print serviceprice and check.
I am writing an app with Android Studio and I want to split a text into different values.
I have following text in result
*"Name: Peter;Age: 25; City: Chicago"*
I want to get:
*Name = Peter;
Age = 25;
City = Chicago;*
I used the search function and found these solutions: Android Split string but for my problem it seems to be too complicated.
The easiest way is to use split() method.
String s1="Name: Peter;Age: 25; City: Chicago";
String[] words=s1.split(";");
//using java foreach loop to print elements of string array
for(String w:words)
{
Log.i("Words: ", w);
}
I have an app which contain mobile number edit text in which user can edit mobile number and I have to send two request to server like:- mobile number and mssdn,mobile number(which is full lenghth ) and mssdn(which contain mobile number last 4 digit).How can I do that
Try this. Check for length greater than 4 before calling subString to avoid IndexOutOfBounds Exception.
EditText mEdtPhoneNumber = (EditText) findViewById(R.id.edtPhoneNumber);
String phoneNumber = mEdtPhoneNumber.getText().toString().trim();
String strLastFourDi = phoneNumber.length() >= 4 ? phoneNumber.substring(phoneNumber.length() - 4): "";
Also what is mssdn?? Is it msisdn??
Use the modulus (%) operator:
To get the last digit: use number % 10
To get the last 2 digits: use number % 100
and so on
For example:
42455%10000 = 2455
You could do something like this:
EditText phoneNumberEditText = (EditText) findViewById(R.id.phoneNumberEditText);
String phoneNumber = phoneNumberEditText.getText().toString();
String lastFourDigits = phoneNumber.substring(phoneNumber.length() - 4);
you should use regex because this will only give you result if the last four letters are actually numbers on the other hand the substring function simply give you last four letters no matter they are numbers or characters. e.g 4344sdsdss4 will give you dss4 which is clearly not a part of phone number
String str="4444ntrjntkr555566";
Pattern p = Pattern.compile("(\\d{4})$");
Matcher m = p.matcher(str);
if (m.find()) {
System.out.println(m.group(m.groupCount()));
}
this will produce 5566
Working
//d mean digits
{4} for fix length as 4
$ mean at the end
List<Integer> f(String str){
ArrayList<Integer> digits = new ArrayList<>();
if (null == str || str.length() < 4){
Log.i(LOG_TAG, "there are less than 4 digits");
return digits;
}
String digitsStr = str.substring(str.length() - 4);
for (char c : digitsStr.toCharArray()){
try {
Integer digit = Integer.parseInt(String.valueOf(c));
digits.add(digit);
} catch (Exception e){
continue;
}
}
return digits;
}
We can also use a new method introduced in kotlin: takeLast(n)
fun getLastDigit(data: String, n:Int): String {
return if(data.length > n){
data.takeLast(n)
}else {
""
}
}
I was wondering how I could programmatically edit strings in android. I am displaying strings from my device to my website, and the apostrophes ruin the PHP output. so in order to fix this, I needed to add character breaks, ie: the backslash '\'.
For example, if I have this string: I love filiberto's!
I need android to edit it to: I love filiberto\'s!
However, each string is going to be different, and there will also be other characters that I have to escape from . How can I do this?
I was wondering how I could programmatically edit strings in android. I am displaying strings from my device to my website, and the apostrophes ruin the PHP output. so in order to fix this, I needed to add character breaks, ie: the backslash '\'.
This is what I have so far, thanks to ANJ for base code...:
if(title.contains("'")) {
int i;
int len = title.length();
char[] temp = new char[len + 1]; //plus one because gotta add new
int k = title.indexOf("'"); //location of apostrophe
for (i = 0; i < k; i++) { //all the letters before the apostrophe
temp[i] = title.charAt(i); //assign letters to array based on index
}
temp[k] = 'L'; // the L is for testing purposes
for (i = k+1; i == len; i++) { //all the letters after apostrophe, to end
temp[i] = title.charAt(i); //finish the original string, same array
}
title = temp.toString(); //output array to string (?)
Log.d("this is", title); //outputs gibberish
}
Which outputs random characters.. not even similar to my starting string. Does anyone know what could be causing this? For example, the string "Lol'ok" turns into >> "%5BC%4042ed0380"
I am assuming you are storing the string somewhere. Lets say the string is: str.
You can use a temporary array to add the '/'. For a single string:
int len = str.length();
char [] temp = new char[len+1]; //Temporary Array
int k = str.indexOf("'"), i; //Finding index of "'"
for(i=0; i<k-1; i++)
{
temp[i] = str.charAt(i); //Copying the string before '
}
temp[k] = '/'; //Placing "/" before '
for(i=k; j<len; j++)
{
temp[i+1] = str.charAt(i); //Copying rest of the string
}
String newstr = temp.toString(); //Converting array to string
You can use the same for multiple strings. Just make it as a function and call it whenever you want.
The String API has a number of API calls that could help, for example String.replaceAll. But...
apostrophes ruin the PHP output
Then fix the PHP code rather than require "clean" input. Best option would be to select a well supported transport format (say JSON or XML) and let the Json API on each end handle escape code.