TextField.text is assigned with a multi-line string, but they're not equal right after the assignment - string

I have an Array of strings:
private var phrase:Array = ["You will be given a series of questions like this:\n2 + 2 =\n(click or press ENTER to continue)","You can use the Keyboard or Mouse\nto deliver the answer\n\"ENTER\" locks it in.\n(click or press ENTER to continue)","\nClick Here\n to start."];
I have a conditional later in the script to see if the phrase[0] is equal to the instructText.text, so I put a "test" directly after the assignment as below:
instructText.text = phrase[0];
if (instructText.text == phrase[0]) {
trace("phrase zero");
}
else {
trace("nottttttttt");
}
//OUTPUT: nottttttttt
I've tried various combinations of phrase[0] as String and String(phrase[0]), but haven't had any luck.
What am I missing?

Turns out that the text property of the TextField class converts the "Line Feed" characters (the "\n", ASCII code of 1010=A16) to the character of "Carriage Return" (the ASCII code of 1310=D16).
So, you need a LF to CR conversion (or vise-versa) to make a homogeneous comparison of what is stored in the property against what you have in the array element:
function replaceLFwithCR(s:String):String {
return s.replace(/\n/g, String.fromCharCode(13));
}
if (instructText.text == replaceCRwithLF(phrase[0])) {
trace("They are equal :)");
}
else {
trace("They are NOT equal :(");
}
// Output: They are equal :)
P.S. To get the code of a character, you may utilize the charCodeAt() method of the String class:
trace("\n".charCodeAt(0)); // 10

Related

Replace some characters in a string with the next unicode character

I have an input text as following:
inputtext = "This is a test";
I need to replace some of the character (based on a certain criteria) to next unicode character
let i = 0;
for c in inputtext.chars() {
if (somecondition){
// Replace char here
inputtext.replace_range(i..i+1, newchar);
// println!("{}", c);
}
What is the best way to do this?
You can't easily update a string in-place because a Rust string is not just an array of characters, it's an array of bytes (in UTF-8 encoding), and different characters may use different numbers of bytes. For example, the character ߿ (U+07FF "Nko Taman Sign") uses two bytes, whereas the next Unicode character ࠀ (U+0800 "Samaritan Letter Alaf") uses three.
It's therefore simplest to turn the string into an iterator of characters (using .chars()), manipulate that iterator as appropriate, and then construct a new string using .collect().
For example:
let old = "abcdef";
let new = old.chars()
// note: there's an edge case if ch == char::MAX which we must decide
// how to handle. in this case I chose to not change the
// character, but this may be different from what you need.
.map(|ch| {
if somecondition {
char::from_u32(ch as u32 + 1).unwrap_or(ch)
} else {
ch
}
})
.collect::<String>();

Making sure every Alphabet is in a string (Kotlin)

So I have a question where I am checking if a string has every letter of the alphabet in it. I was able to check if there is alphabet in the string, but I'm not sure how to check if there is EVERY alphabet in said string. Here's the code
fun isPangram (pangram: Array<String>) : String {
var panString : String
var outcome = ""
for (i in pangram.indices){
panString = pangram[i]
if (panString.matches(".^*[a-z].*".toRegex())){
outcome = outcome.plus('1')
}
else {outcome = outcome.plus('0')}
}
return outcome
}
Any ideas are welcomed Thanks.
I think it would be easier to check if all members of the alphabet range are in each string than to use Regex:
fun isPangram(pangram: Array<String>): String =
pangram.joinToString("") { inputString ->
when {
('a'..'z').all { it in inputString.lowercase() } -> "1"
else -> "0"
}
}
Hi this is how you can make with regular expression
Kotlin Syntax
fun isStrinfContainsAllAlphabeta( input: String) {
return input.lowercase()
.replace("[^a-z]".toRegex(), "")
.replace("(.)(?=.*\\1)".toRegex(), "")
.length == 26;
}
In java:
public static boolean isStrinfContainsAllAlphabeta(String input) {
return input.toLowerCase()
.replace("[^a-z]", "")
.replace("(.)(?=.*\\1)", "")
.length() == 26;
}
the function takes only one string. The first "replaceAll" removes all the non-alphabet characters, The second one removes the duplicated character, then you check how many characters remained.
Just to bounce off Tenfour04's solution, if you write two functions (one for the pangram check, one for processing the array) I feel like you can make it a little more readable, since they're really two separate tasks. (This is partly an excuse to show you some Kotlin tricks!)
val String.isPangram get() = ('a'..'z').all { this.contains(it, ignoreCase = true) }
fun checkPangrams(strings: Array<String>) =
strings.joinToString("") { if (it.isPangram) "1" else "0" }
You could use an extension function instead of an extension property (so it.isPangram()), or just a plain function with a parameter (isPangram(it)), but you can write stuff that almost reads like English, if you want!

Get String Between 2 Strings with Arduino

I am looking for a way to get a String between 2 Strings using Arduino. This is the source String:
Hello, my name is John Doe# and my favourite number is 32#.
The output has to be:
String name = "John Doe"; //Between "name is " and "#"
String favouriteNumber = "32"; //Between "number is " and "#"
How can this be achieved with Arduino?
I am not able to find any information online about this. Those examples for C are not working anyway. I understand that using String is not recommended in Arduino, but I have to do it this way to make things simpler.
By the way, this method of using a '#' to indicate the end of the data is not an ideal way to do it as I would like the input to be more human readable and more natural. Would anyone please suggest another way to do this as well?
Thanks in advance!
Function midString find the substring that is between two other strings "start" and "finish". If such a string does not exist, it returns "". A test code is included too.
void setup() {
test();
}
void loop() {
delay(100);
}
String midString(String str, String start, String finish){
int locStart = str.indexOf(start);
if (locStart==-1) return "";
locStart += start.length();
int locFinish = str.indexOf(finish, locStart);
if (locFinish==-1) return "";
return str.substring(locStart, locFinish);
}
void test(){
Serial.begin(115200);
String str = "Get a substring of a String. The starting index is inclusive (the corresponding character is included in the substring), but the optional ending index is exclusive";
Serial.print(">");
Serial.print( midString( str, "substring", "String" ) );
Serial.println("<");
Serial.print(">");
Serial.print( midString( str, "substring", "." ) );
Serial.println("<");
Serial.print(">");
Serial.print( midString( str, "corresponding", "inclusive" ) );
Serial.println("<");
Serial.print(">");
Serial.print( midString( str, "object", "inclusive" ) );
Serial.println("<");
}
just searched for this and saw no answer so i cooked one up.
i prefer working with String as well because of code readability and simplicity.
for me its more important than squeezing every last drop of juice out of my arduino.
String name = GetStringBetweenStrings("Hello, my name is John Doe# and my favourite number is 32#." ,"name is ","#");
String GetStringBetweenStrings(String input, String firstdel, String enddel){
int posfrom = input.indexOf(firstdel) + firstdel.length();
int posto = input.indexOf(enddel);
return input.substring(posfrom, posto);
}
watch out for the first case its fine, but for the second one you would have to change the second filter sting to "#." so it doesn't use the first occurrence of the #

Using loops to go through string and check char as a dict key

so I want to kind of build a "Decrypter", I have a dictionary with the keys being the symbol, and the value the respective value for the symbol, then I have this string that the code is suppose to look into, the translate will be saved in a other string, in this case called output. This is the way I did the loop part, but is not working:
var outputText = " "
for character in textForScan{
for key in gematriaToLetters{
if (gematriaToLetters.keys == textForScan[character]){
outputText.insert(gematriaToLetters.values, atIndex: outputText.endIndex)
}
}
}
You could also consider using map:
let outputText = "".join(map(textForScan) { gematriaToLetters[String($0)] ?? String($0) })
If you don't specify a specific letter in the dictionary it returns the current letter without "converting".
I think you are looking for something like this:
for aCharacter in textForScan {
let newChar = gematrialToLetters["\(aCharacter)"]
outputText += newChar
}
print(outputText)

Validate if a text has only letters and spaces

I'm new to programming and I'm using Dart for a “introduction to programming“ course.
I'd like to write a code to validate if a text has only letter and space. I've found this for validate spaces.
function validate() {
var field = document.getElementById("myField");
if (field.value.replace(/ /g, "").length == 0) {
alert("Please enter some data (not spaces!)");
}
}
Thanks in advance, also I would need to write a string variable with sentences of different lengths and a function that finds the longest sentence. Any pointers?
[^a-z ] matches anything that is not a lowercase letter or space. caseSensitive: false makes it not match upper case either.
RegExp exp = new RegExp(r"[^a-z ]", caseSensitive: false);
print(exp.allMatches("this is valid").length == 0);
print(exp.allMatches("ThIs Is VaLiD").length == 0);
print(exp.allMatches("Th1s 1s NOT val1d").length == 0);
You can use exp.allMatches("string").length to find the number of characters that are not alpha or whitespace. so you can use:
if (exp.allMatches(field.value).length > 0) {
alert("Please enter some data (not spaces!)");
}

Resources