Comparing sentences (strings) in AS3 - string

I'm building a short quiz where the user needs to input the meaning of an acronym.
This means I need to compare a long string (usually a sentence) typed in by the user with an acronym.
I have a feeling I'm not doing it right. For my testing I'm copy-pasting the correct answer to make sure the spelling is correct however I keep getting the feedback that the answer is incorrect.
My question is, am I comparing correctly?
Here's my code:
var arrQuestions:Array = [["LOL","Laughing Out Loud"], ["OMG", "Oh My God"], ["BTW", "By The Way"]];
var i:Number=0;
function setup():void {
quiztext_txt.text = arrQuestions[i][0];
trace(quiztext_txt.text);
trace(arrQuestions[i][1]);
check_btn.addEventListener(MouseEvent.CLICK, clickHandler);
}//End of Setup()
setup();
function clickHandler(event:MouseEvent):void {
var givenString:String;
var inputString:String;
inputString = userinput_txt.text;
givenString = arrQuestions[i][1];
if (inputString == givenString) {
feedback_txt.text = "Correct!";
} else {
feedback_txt.text = "Wrong!";
}
}

Is there any whitespace before/after the user input? Is the value of i changing in between?
else
{
//what does it trace?
trace("given answer: " + inputString + "\ncorrect answer: " + givenString);
feedback_txt.text = "Wrong!";
}

try clearing the text field in your setup function like so:
function setup():void
{
userinput_txt.text = "";
quiztext_txt.text = arrQuestions[i][0];
trace(quiztext_txt.text);
trace(arrQuestions[i][1]);
check_btn.addEventListener(MouseEvent.CLICK, clickHandler);
}//End of Setup()

For any kind of string matching I would strongly recommend looking into regular expressions (RegExp). In the regular expression written below I am matching each word, then I say [ ]+ which means "at least one or more spaces", then at the end of the expression I use /gi to say that the expression is case insensitive. In the code above if I type the phrase in lowercase its not going to match, a quick fix for this would be to use this if(inputString.toLowerCase() == givenString.toLowerCase()) which would catch this. Heres the regexp example:
// testString could easily equal myTextField.text
var testString:String = "lauGHing OuT loUD";
// you could store each one in an array, as you were before
var regEx:RegExp = /laughing[ ]+out[ ]+loud/gi
trace( regEx.test( testString ) ); //returns true,test() returns a Boolean
Hope this helps.

Related

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 the first line of a string in haxe

Let's assume we have a multiline string, like
var s:String = "my first line\nmy second line\nmy third line\nand so on!";
What is the best way to get (only) the first line of this string in Haxe? I know I can do something like:
static function getFirstLine(s:String):String {
var t:String = s.split("\n")[0];
if(t.charAt(t.length - 1) == "\r") {
t = t.substring(0, t.length - 1);
}
return t;
}
However I'm wondering if there is any easier (predefined) method for this ...
Caveat that #Gama11's answer works well and is more elegant than this.
If your string is long, split will iterate over the whole thing and allocate an array containing every line in your string, both of which are unnecessary here. Another option would be indexOf:
static function getFirstLine(s:String):String {
var i = s.indexOf("\n");
if (i == -1) return s;
if (i > 0 && s.charAt(i - 1) == "\r") --i;
return s.substr(0, i);
}
There's no built-in utility in the standard library for this that I know of, but you make it a bit more elegant and avoid the substring() handling for \r by splitting on a regex:
static function getFirstLine(s:String):String {
return ~/\r?\n/.split(s)[0];
}
The regex \r?\n optionally matches a carriage return followed by a line feed character.

Comparing Strings in As3

I'm currently coding a game for an assignment and I need help comparing Strings.
The question in the game asks the users to type out a specific sequence on their keyboard. I have provided a sequence "SWAGAFFAD" and I want my code to compare a the values that people might enter. If they get the sequence correct I want them to be able to proceed to the next question and if they don't type in the exact sequence they just get an error message come up. Just not sure how to code this. Can someone help me out? Assuming I'd need an IF ELSE statement??
Thanks in advance!!!
Use the == and != operators to compare strings with each other and to compare strings with other types of objects, as the following example shows:
var str1:String = "1";
var str1b:String = "1";
var str2:String = "2";
trace(str1 == str1b); // true
trace(str1 == str2); // false
var total:uint = 1;
trace(str1 == total); // true
for more detail info adobe doc
You can use ObjectUtil.compare(string1,string2). It will return 0 if both the strings are equal else 1 or -1
Yes you might want to use if-else statement and == operator as others suggested. Here's one very simple way:
var word:String = "SWAGAFFAD";
var index:int = 0;
stage.addEventListener(KeyboardEvent.KEY_UP, keyUp);
function keyUp(e:KeyboardEvent):void{
if(String.fromCharCode(e.keyCode) == word.split("")[index]){
index++;
trace("Correct letter!");
if(index == word.length){
//Player got the whole word, proceed to next one
}
}else{
//Wrong letter, do something else
}
}

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)

Is there a .NET function to remove the first (and only the first) occurrence at the start of a string?

I was using the TrimStart function to do the following:
var example = "Savings:Save 20% on this stuff";
example = example.TrimStart("Savings:".ToCharArray());
I was expecting this to result in example having a value of "Save 20% on this stuff".
However, what I got was "e 20% on this stuff".
After reading the documentation on TrimStart I understand why, but now I'm left wondering if there is a function in .NET that does what I was trying to do in the first place?
Does anyone know of a function so I don't have to create my own and keep track of it?
I don't think such a method exists but you can easily do it using StartsWith and Substring:
s = s.StartsWith(toRemove) ? s.Substring(toRemove.Length) : s;
You can even add it as an extension method:
public static class StringExtension
{
public static string RemoveFromStart(this string s, string toRemove)
{
if (s == null)
{
throw new ArgumentNullException("s");
}
if (toRemove == null)
{
throw new ArgumentNullException("toRemove");
}
if (!s.StartsWith(toRemove))
{
return s;
}
return s.Substring(toRemove.Length);
}
}
No, I don't believe there's anything which does this built into the framework. It's a somewhat unusual requirement, IMO.
Note that you should think carefully about whether you're trying to remove "the first occurrence" or remove the occurrence at the start of the string, if there is one. For example, think what you'd want to do with: "Hello. Savings: Save 20% on this stuff".
You can do that quite easily using a regular expression.
Remove the occurrence on the beginning of the string:
example = Regex.Replace(example, #"^Savings:", "");
Remove the first occurrence in the string:
example = Regex.Replace(example, #"(?<!Savings:.*)Savings:", "");

Resources