string.contains is always returning true - string

I made a program that takes a text file, stores the lines as strings in an array. Now I want to "filter" those entries of the array.
I am using the string.contains to see if each array entry has the substring "05/Aug".
For some reason, it is always returning true, when in fact, it should not.
Here is the file: http://www.santarosa.edu/~lmeade/weblog.txt
And here is my code:
for (int i=0; i<10;i++)
{
boolean check = storestrings[i].contains("05/Aug");
if(check = true){
teststring[i] = storestrings[i];
//System.out.print(storestrings[i]);
}
else{
teststring[i] = null;
}
}

You used assignment operator in the if statement instead of equality. It should be like this:
if(check == true){
teststring[i] = storestrings[i];
//System.out.print(storestrings[i]);
}
or simply
if (check) {
teststring[i] = storestrings[i];
//System.out.print(storestrings[i]);
}
In your code, when it reached check = true in the if statement, it assigns true to the check variable and returns true so the if condition always evaluates to true.

Related

Flutter converting String to Boolean

I am having a String that i would like to convert to Boolean Below is how the string looks like
String isValid = "false";
The String isValid can either be true or false
Is there a way i can directly convert this String isValid to Boolean. I have tried Sample questions and solutions but they are just converting Strings which are hard coded, for example most of the answers are just when the string is true
On top of my head, you can create an extension method for string data-type for your own need with all sorts of requirements checks and custom exceptions to beautify your desired functionalities. Here is an example:
import 'package:test/expect.dart';
void main(List<String> args) {
String isValid = "true";
print(isValid.toBoolean());
}
extension on String {
bool toBoolean() {
print(this);
return (this.toLowerCase() == "true" || this.toLowerCase() == "1")
? true
: (this.toLowerCase() == "false" || this.toLowerCase() == "0"
? false
: throwsUnsupportedError);
}
}
Here, in this example, I've created a variable named isValid in the main() method, which contains a string value. But, look closely at how I've parsed the string value to a bool value using the power with extension declared just a few lines below.
Same way, you can access the newly created string-extension method toBoolean() from anywhere. Keep in mind, if you're not in the same file where the toBoolean() extension is created, don't forget to import the proper reference.
Bonus tips:
You can also access toBoolean() like this,
bool alternateValidation = "true".toBoolean();
Happy coding 😊
This example can work for you, either if is false or true:
String isValid = "true";
bool newBoolValue = isValid.toLowerCase() != "false";
print(newBoolValue);
You can use extensions like this
bool toBoolean() {
String str = this!;
return str != '0' && str != 'false' && str != '';
}
First of All
You should make the string to lowercase to prevent check the string twice
then you can check if the string equal "true" or not and save the result to bool variable as below:
String isValidString = "false"; // the boolean inside string
bool isValid = isValidString.toLowerCase() == 'true'; // check if true after lowercase
print("isValid=$isValid"); // print the result
I opened a PR for this question, I believe that in the future it will be possible to do something native.
void main() {
print(bool.parse("true")); // true
print(bool.parse("false")); //false
print(bool.parse("TRUE")); // FormatException
print(bool.parse("FALSE")); //FormatException
print(bool.parse("True", caseSensitive: false)); // true
print(bool.parse("False", caseSensitive: false)); // false
if(bool.parse("true")){
//code..
}
}
Reference
https://github.com/dart-lang/sdk/pull/51026

TWIG: Get the first item fulfilling a condition

I need to display the first item that fulfills some condition. Something I would normally do via construction like this pseudocode:
for(item in some_array)
if(some_condition(item)) {
some_action();
break;
}
The problem is I need to do that in TWIG and TWIG does not allow to break a for loop. How to do that then?
You could use a boolean to denote that you have processed the first item but it will continue to loop over the rest of the array:
set firstItemProcessed = false;
for(item in some_array) {
if(firstItemProcessed == false and some_condition(item) ) {
some_action();
firstItemProcessed = true;
}
}

How check if a list contains value or key inside a another list in Groovy?

How can I check if a list contains a key or value inside a sublist (of sublist ..) or in the "root"
And is possible to get a the "path"?
This containsValue or containsKey seems only to look in the root of the list
Example pseudo:
//This is my list
list = [languages:[_clazz:"basics.i18n.Language", messages:[_clazz:"basics.i18n.Message"]]]
list.containsKey("languages") // return true
list.containsValue("basics.i18n.Language") // return false where I want true
list.containsKey("messages") // return false // return false where I want true
list.containsValue("basics.i18n.Message") // return false where I want true
There's nothing in Groovy for this I don't think, but you can write your own and add them to Map (what you have is a Map, not a List as you have named the variable)
Map.metaClass.deepContainsKey = { value ->
delegate.containsKey(value) ?:
delegate.values().findAll { it instanceof Map }.findResult { it.deepContainsKey(value) } ?:
false
}
Map.metaClass.deepContainsValue = { value ->
delegate.containsValue(value) ?:
delegate.values().findAll { it instanceof Map }.findResult { it.deepContainsValue(value) } ?:
false
}
Then, given your map:
def map = [languages:[_clazz:"basics.i18n.Language", messages:[_clazz:"basics.i18n.Message"]]]
All of these assertions pass:
assert map.deepContainsKey("messages")
assert map.deepContainsValue("basics.i18n.Message")
assert map.deepContainsValue("basics.i18n.Language")
assert !map.deepContainsKey("missing")
assert !map.deepContainsValue("novalue")

How to Handle textbox values on sever side

I have three textboxes.In textbox1 and in textbox2 i entered a number Like ->
Textbox1-0123456789
Textbox2-0123-456-789
Textboxe3-0123-456-789
Now on server side i.e on aspx.cs page i need to check the numbers is it same or not and only one distinct number will be saved in database
//Get the values from text box and form a list
//validate against a regular expression to make them pure numeric
//now check if they are all same
List<string> lst = new List<string>()
{
"0123-456-A789",
"0123-456-A789",
"0123-456-789"
};
Regex rgx = new Regex("[^a-zA-Z0-9]");
//s1 = rgx.Replace(s1, "");
for (int i = 0; i < lst.Count; i++)
{
var value = lst[i];
value = rgx.Replace(value, "");
lst[i] = value;
}
if (lst.Any(num => num != lst[0]))
{
Console.WriteLine("All are not same");
}
else
{
Console.WriteLine("All are same");
}
//if all are same, pick an entry from the list
// if not throw error
HOPE THIS MAY GIVE U AN IDEA !!!!
If we apply replace("-","") than from every textbox it will remove dash.The number which is same like in
textbox1-0123456789
textbox2=0123-456-789
textbox3=678-908-999
than replace will remove dash from textbox3 also which we dont want.
so For this we have to apply not exists operation of linq.
List strMobileNos = new List();
Regex re = new Regex(#"\d{10}|\d{3}\s*-\s*\d{3}\s*-\s*\d{4}");
!strMobileNos.Exists(l => l.Replace("-", "") == Request.Form["txtMobNo2"].Replace("Mobile2", "").Replace("-", ""))

Groovy equivalent to OCL forAll

What is the Groovy equivalent to the forAll method in OCL?
Let's say that I have a list of items.
def items = new LinkedList<Item>();
What is the Groovy way to express a predicate that holds if and only if all items match a certain criteria?
The following code snippet does not work, because the inner return only jumps out of the current iteration of the each closure, not out of the forAll method.
boolean forAll(def items)
{
items.each { item -> if (!item.matchesCriteria()) return false; };
return true;
}
The following code snippet, which should do the trick, feels cumbersome and not Groovy-like.
boolean forAll(def items)
{
boolean acceptable = true;
items.each { item -> if (!item.matchesCriteria()) acceptable = false; };
return acceptable;
}
I am looking for a way to lazily evaluate the predicate, so that the evaluation would finish when a first non-matching item is found.
You can use every
items.every { it.matchesCriteria() }
In groovy that's very easy:
def yourCollection = [0,1,"", "sunshine", true,false]
assert yourCollection.any() // If any element is true
or if you want to make sure, all are true
assert !yourCollection.every()
you can even do it with a closure
assert yourCollection.any { it == "sunshine" } // matches one element, and returns true
or
assert !yourCollection.every { it == "sunshine" } // does not match all elements

Resources