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

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)

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!

Grails convert String to Map with comma in string values

I want convert string to Map in grails. I already have a function of string to map conversion. Heres the code,
static def StringToMap(String reportValues){
Map result=[:]
result=reportValues.replace('[','').replace(']','').replace(' ','').split(',').inject([:]){map,token ->
List tokenizeStr=token.split(':');
tokenizeStr.size()>1?tokenizeStr?.with {map[it[0]?.toString()?.trim()]=it[1]?.toString()?.trim()}:tokenizeStr?.with {map[it[0]?.toString()?.trim()]=''}
map
}
return result
}
But, I have String with comma in the values, so the above function doesn't work for me. Heres my String
[program_type:, subsidiary_code:, groupName:, termination_date:, effective_date:, subsidiary_name:ABC, INC]
my function returns ABC only. not ABC, INC. I googled about it but couldnt find any concrete help.
Generally speaking, if I have to convert a Stringified Map to a Map object I try to make use of Eval.me. Your example String though isn't quite right to do so, if you had the following it would "just work":
// Note I have added '' around the values.
​String a = "[program_type:'', subsidiary_code:'', groupName:'', termination_date:'', effective_date:'', subsidiary_name:'ABC']"
Map b = Eval.me(a)​
// returns b = [program_type:, subsidiary_code:, groupName:, termination_date:, effective_date:, subsidiary_name:ABC]
If you have control of the String then if you can create it following this kind of pattern, it would be the easiest solution I suspect.
In case it is not possible to change the input parameter, this might be a not so clean and not so short option. It relies on the colon instead of comma values.
​String reportValues = "[program_type:, subsidiary_code:, groupName:, termination_date:, effective_date:, subsidiary_name:ABC, INC]"
reportValues = reportValues[1..-2]
def m = reportValues.split(":")
def map = [:]
def length = m.size()
m.eachWithIndex { v, i ->
if(i != 0) {
List l = m[i].split(",")
if (i == length-1) {
map.put(m[i-1].split(",")[-1], l.join(","))
} else {
map.put(m[i-1].split(",")[-1], l[0..-2].join(","))
}
}
}
map.each {key, value -> println "key: " + key + " value: " + value}
BTW: Only use eval on trusted input, AFAIK it executes everything.
You could try messing around with this bit of code:
String tempString = "[program_type:11, 'aa':'bb', subsidiary_code:, groupName:, termination_date:, effective_date:, subsidiary_name:ABC, INC]"
List StringasList = tempString.tokenize('[],')
def finalMap=[:]
StringasList?.each { e->
def f = e?.split(':')
finalMap."${f[0]}"= f.size()>1 ? f[1] : null
}
println """-- tempString: ${tempString.getClass()} StringasList: ${StringasList.getClass()}
finalMap: ${finalMap.getClass()} \n Results\n finalMap ${finalMap}
"""
Above produces:
-- tempString: class java.lang.String StringasList: class java.util.ArrayList
finalMap: class java.util.LinkedHashMap
Results
finalMap [program_type:11, 'aa':'bb', subsidiary_code:null, groupName:null, termination_date:null, effective_date:null, subsidiary_name:ABC, INC:null]
It tokenizes the String then converts ArrayList by iterating through the list and passing each one again split against : into a map. It also has to check to ensure the size is greater than 1 otherwise it will break on f[1]

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

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

Swift - Finding a substring between two locations in a string

I have a string that is formatted like this: "XbfdASF;FBACasc|Piida;bfedsSA|XbbnSF;vsdfAs|"
Basiclly its an ID;ID| and then it repeats.
I have the first ID and I need to find it's partner Example: I have 'Piida' and I need to find the String that follows it after the ';' which is 'bfedsSA'
How do I do this?
The problem I am having is that the length of the IDs is dynamic so I need to get the index of '|' after the ID I have which is 'Piida' and then get the string that is between these indexes which in this case should be 'bfedsSA'.
There are many ways to do this, but the easiest is to split the string into an array using a separator.
If you know JavaScript, it's the equivalent of the .split() string method; Swift does have this functionality, but as you see there, it can get a little messy. You can extend String like this to make it a bit simpler. For completeness, I'll include it here:
import Foundation
extension String {
public func split(separator: String) -> [String] {
if separator.isEmpty {
return map(self) { String($0) }
}
if var pre = self.rangeOfString(separator) {
var parts = [self.substringToIndex(pre.startIndex)]
while let rng = self.rangeOfString(separator, range: pre.endIndex..<endIndex) {
parts.append(self.substringWithRange(pre.endIndex..<rng.startIndex))
pre = rng
}
parts.append(self.substringWithRange(pre.endIndex..<endIndex))
return parts
} else {
return [self]
}
}
}
Now, you can call .split() on strings like this:
"test".split("e") // ["t", "st"]
So, what you should do first is split up your ID string into segments by your separator, which will be |, because that's how your IDs are separated:
let ids: [String] = "XbfdASF;FBACasc|Piida;bfedsSA|XbbnSF;vsdfAs|".split("|")
Now, you have a String array of your IDs that would look like this:
["XbfdASF;FBACasc", "Piida;bfedsSA", "XbbnSF;vsdfAs"]
Your IDs are in the format ID;VALUE, so you can split them again like this:
let pair: [String] = ids[anyIndex].split(";") // ["ID", "VALUE"]
You can access the ID at index 0 of that array and the value at index 1.
Example:
let id: String = ids[1].split(";")[0]
let code: String = ids[1].split(";")[1]
println("\(id): \(code)") // Piida: bfedsSA

Comparing sentences (strings) in AS3

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.

Resources