I want to check if the first letter of string is in uppercase in Dart language. How can I implement it? Thanks in advance.
The simplest way I can think of is to compare the first letter of the string with the uppercase equivalent of it. Something like:
bool isUpperCase(String string) {
if (string == null) {
return false;
}
if (string.isEmpty) {
return false;
}
if (string.trimLeft().isEmpty) {
return false;
}
String firstLetter = string.trimLeft().substring(0, 1);
if (double.tryParse(firstLetter) != null) {
return false;
}
return firstLetter.toUpperCase() == string.substring(0, 1);
}
Updated the answer to take in consideration digits.
Also #Saed Nabil is right, this solution will return true if the string starts with any character that is not a letter (except for digits).
You can use the validators library if you are not already using it.
Then use this method
isUppercase(String str) → bool
check if the string str is uppercase
Don't forget to import the dependency, see documentation, to the pubspec.yaml and to your code import 'package:validators/validators.dart';.
Example code:
if(isUppercase(value[0])){
... do some magic
}
You should check that the value is not empty and not null first for safety. Like this:
if(value != null && value.isNotEmpty && isUppercase(value[0])){
... do amazing things
}
check this code it will return the actual uppercase letter else will return null
void main(){
var myString = "1s you said";
var firstCapital = firstCapitalLetter(myString);
if( firstCapital != null){
print("First Capital Letter is ${firstCapital}");
}else{
print("Not found");
}
}
String firstCapitalLetter(String myString){
final allCapitals = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //string.substring(0, 1).toUpperCase() == string.substring(0, 1) will not work with for ex. numbers;
if (myString == null) {
return null;
}
if (myString.isEmpty) {
return null;
}
if (myString.trimLeft().isEmpty) {
return null;
}
if( allCapitals.contains(myString[0])){
return myString[0];
}else{
return null;
}
}
this is a typical case for Optional type of Java language , please check this library if you prefer functional style code
optional package
bool isUppercase(String str){
return str == str.toUpperCase();
}
This seems to be elegant way for checking uppercase
String s='Hello';
bool isUpper = isUppercase(s[0]);
print(isUpper); //true
isUpper = isUppercase(s[1]);
print(isUpper); //false
Add this extension
extension Case on String{
// isuppercase
bool isUpperCase(){
int ascii = codeUnitAt(0);
return ascii >= 65 && ascii <= 90;
}
// islowercase
bool isLowerCase(){
int ascii = codeUnitAt(0);
return ascii >= 97 && ascii <= 122;
}
}
use it like this
String letter = 'A';
print(letter.isUpperCase()); // true
Related
In Javascript when I want to end a function I usually write return, but in the dart, if I do that then the function asks for a return statement at the end of each branch which is messy.
Function createCategory(File image) {
String title = _categoryTitle.value;
if(image == null || title == null || title.length == 0) {
return null;
}
CategoryModel newCategory = new CategoryModel();
if(_categories.value == null) {
_categories.sink.add([newCategory]);
}
return null;
}
What is the correct way to do this in dart?
I think your confusion comes from that your method is valid Dart code but does not really do what I guess you think. Your method has the following signature:
Function createCategory(File image) {
This means your method is named createCategory, takes one argument of the type File and returns a Function. Since you have marked the method to return a Function, then Dart will tell you it is a problem if you just return; since this is properly not what you wanted.
If your method is not going to return any value, then you want to mark this with the return type of void like:
void createCategory(File image) {
String title = _categoryTitle.value;
if (image == null || title == null || title.length == 0) {
return;
}
CategoryModel newCategory = new CategoryModel();
if (_categories.value == null) {
_categories.sink.add([newCategory]);
}
return;
}
I should note, that the last return can be skipped since Dart will automatically add return; at the end of a function if it is missing.
you can do that like this:
void createCategory(File image) {
String title = _categoryTitle.value;
if (image != null && title.isNotEmpty && _categories.value == null) {
_categories.sink.add([CategoryModel()]);
}
}
While making my project I stuck on a problem.
I have the following thing:
This is in my PostComment action
comment = Emoticon.Format(comment);
Emoticon is public class.
The Format action return the following:
public static string Format(string input)
{
if (input == null || input.Length == 0)
{
return input;
}
else
{
string result = input;
Emoticon[] all = All;
foreach (Emoticon emoticon in all)
{
string a;
string a_;
int border;
// Decide whether a link is required.
if (emoticon.Url != null && emoticon.Url.Length > 0)
{
a = string.Format("<a href=\"{0}\">", emoticon.Url);
a_ = "</a>";
border = 1;
}
else
{
a = "";
a_ = "";
border = 0;
}
// Replace this emoticon.
string replacement =
string.Format(
"{0}<img src=\"{1}\" alt=\"{2}\" align=\"AbsMiddle\" border=\"{3}\" />{4}",
a,
emoticon.VirtualPath,
HttpUtility.HtmlEncode(emoticon.Title),
border,
a_);
result = result.Replace(emoticon.Shortcut, replacement);
}
return result;
}
}
And from PostComment action I go to view and print the comment:
<div class="panel-body">#comment.Content</div>
But my problem is in string.Format(
"{0}<img src=\"{1}\" alt=\"{2}\" align=\"AbsMiddle\" border=\"{3}\" />{4}", because it returns string and in the view it is a string but my purpose is to be a picture. #comment.Comment is also string.
i want compare 2 variable (typed mvcHtmlString) but the response is always false...
#{ //Load the good css file
if (ViewBag.BrowserName == MvcHtmlString.Create("ie"))
{
if (ViewBag.BrowserVersion > 9)
{
#Styles.Render("~/Content/ie10-css")
}
else
{
#Styles.Render("~/Content/ie7-css")
}
}
else if (ViewBag.BrowserName == MvcHtmlString.Create("safari")) //and ipad
{
#Styles.Render("~/Content/safari/css")
}
else //if (ViewBag.BrowserName == "firefox" || ViewBag.BrowserName == "chrome")
{
#Styles.Render("~/Content/default/css")
}
}
My console show :
MvcHtmlString.Create("safari") -> {safari}
ViewBag.BrowserName -> {safari}
ViewBag.BrowserName == MvcHtmlString("safari") -> false
I ask why does it false ?
MvcHtmlString.Create does not create a string instance. The output is the same because it returns the string you used in ToString() implementation. Since MvcHtmlString doesn't overload == operator, they can never be equal.
You can use regular strings for comparison:
if (ViewBag.BrowserName == "ie")
{ ... }
public String GetBrowserName()
{
ViewBag.logged = false;
return (Request.Browser.Browser.ToLowerInvariant());
}
So, the Html.Action returns an MvcHtmlString (i don't know why) but is possible to force it to be a string directly in the cshtml page :
#if (ViewBag.BrowserName == null)
{
ViewBag.BrowserName = Html.Action("GetBrowserName", "Services").ToString();
}
now compare the 2 string :
if (ViewBag.BrowserName == "safari")
in my application i have a Custom text box with BasicEditField.FILTER_NUMERIC. When the user enter the value in the field the comma should be added to the Currency format .
EX:1,234,567,8.... like this.
In my code i tried like this.
protected boolean keyUp(int keycode, int time) {
String entireText = getText();
if (!entireText.equals(new String(""))) {
double val = Double.parseDouble(entireText);
String txt = Utile.formatNumber(val, 3, ",");// this will give the //comma separation format
setText(txt);// set the value in the text box
}
return super.keyUp(keycode, time);
}
it will give the correct number format... when i set the value in the text box it will through the IllegalArgumentException. I know BasicEditField.FILTER_NUMERIC will not allow the charector like comma(,)..
How can i achieve this?
I tried this way and it works fine...
public class MyTextfilter extends TextFilter {
private static TextFilter _tf = TextFilter.get(TextFilter.REAL_NUMERIC);
public char convert(char character, int status) {
char c = 0;
c = _tf.convert(character, status);
if (c != 0) {
return c;
}
return 0;
}
public boolean validate(char character) {
if (character == Characters.COMMA) {
return true;
}
boolean b = _tf.validate(character);
if (b) {
return true;
}
return false;
}
}
and call like this
editField.setFilter(new MyTextfilter());
I have added a BasicEditField to a GridFieldManager. When I test it, it allows input values like 11.11.11. How can I make my BasicEditField accept only correct double numbers, like 101.1 or 123.123. That is, allow only one decimal point.
gfm = new GridFieldManager(1, 2, 0);
gfm.add(new LabelField(" Enter value : "));
bef = new BasicEditField(BasicEditField.NO_NEWLINE|BasicEditField.FILTER_REAL_NUMERIC);
bef.setFilter(TextFilter.get(NumericTextFilter.REAL_NUMERIC));
bef.setFilter(TextFilter.get(TextFilter.REAL_NUMERIC));
bef.setText("1");
bef.setMaxSize(8);
gfm.add(bef);
add(gfm);
i had tried everything that i can. but the problem is yet in my app. can anyone give me a proper way to design a input field tha accepts decimal numbers?
Please add all the objects into the mainScreen with add(field);.
and then trying to get value of that fields.
now in your code put
String s = bef.getText();
Dialog.alert(s);
after
add(gfm);
and
To accept number like 1.1111.
then add
BasicEditField.FILTER_REAL_NUMERIC
in BasicEditFieldConstructor.
Now i think you got your solution.
finally i got the solution for a forum(forgot to copy the link)..
here it is...
inside my class i put the variables...
private int maxIntDigits = -1;
private int maxFractDigits = -1;
private String old;
i had added a BasicEditField, bef..
bef = new BasicEditField("","1");
bef.setMaxSize(8);
bef.setChangeListener(this);
add(bef);
And then in its fieldChanged().
public void fieldChanged(Field field, int context)
{
if(field==bef)
{
String str = bef.getText();
if(str.equals(""))
{
old = "";
//return;
}
if(str.indexOf('.') == str.lastIndexOf('.'))
{
if(str.indexOf('-') >= 0)
{
bef.setText(old);
}
if(validateIntPart(str) && validateFractPart(str))
{
old = str;
//return;
}
else
{
bef.setText(old);
}
}
else
{
bef.setText(old);
//return;
}
}
}
and then two functions in it...
private boolean validateIntPart(String str) {
if(maxIntDigits == -1) {
return true; //no limit has been set
}
int p = str.indexOf('.');
if(p == -1) {
p = str.length();
}
int digits = str.substring(0, p).length();
if(digits > maxIntDigits) {
return false;
} else {
return true;
}
}
private boolean validateFractPart(String str) {
if(maxFractDigits == -1) {
return true; //no limit has been set
}
int p = str.indexOf('.');
if(p == -1) {
return true; //if no '.' found then the fract part can't be too big
}
int digits = str.substring(p + 1, str.length()).length();
if(digits > maxFractDigits) {
return false;
} else {
return true;
}
}