Split string in Lua and print selected keys - string

I'm looking for a little help with splitting a string using Lua and printing selected parts of it. I have this code so far:
b = "an example string"
for i in string.gmatch(b, "%w+") do
print(i)
end
Output is...
an
example
string
How do I go about printing only bits of the result?
I've tried the following but just returns a list of "nils":
b = "an example string"
for i in string.gmatch(b, "%w+") do
print(i[1])
end
So if I wanted to print:
string
example
How would this work? I was pretty sure I just added the value assigned to the key that is in memory, like [0] or [1]. But I must be wrong..
In this use case the sample text will remain the same, only time stamps will change in the string. I just need to reorder the words.
Any help is greatly appreciated :)

The best way I can find is to use the loop to store the matches in an array. Then you can access them with literal indexes:
b = "an example string"
local words = {}
for i in string.gmatch(b, "%w+") do
table.insert(words, i)
end
print(words[3])
print(words[2])

In addition to the existing (probably perferable) answer, you could also do some manual work with a counter:
counter = 0
for i in string.gmatch(b, "%w+") do
counter = counter + 1
if counter > 1 then print(i) end
end
Or, here's a one-liner (that wouldn't scale with larger strings though and also doesn't insert a newline between second and third word):
print(string.match(b, "%w+%s+(%w+)%s+(%w+)"))

Related

Is there a way to get increment counter from a Python 'for' loop with decrement range?

I read everyone uses enumerate, but I don't think I know how to use it in my code. I want to print the value of an alphabet in a string according to alphabet order and the next character will increment the value by 1 and I want to start it from the last character in the string.
I can solve the code, but how can I replace the counter i without using i = i+1 to make this code a bit shorter? Is there a way to implement something in the for loop?
This is my code:
def project(r):
i = 0
for char in range(len(r),0,-1):
print(ord(r[char-1])-96+i)
i=i+1
project(str(input()).lower())
For example, if I insert a string such as "sad", the output will be [4,2,21] because d = 4, a = 1, s = 19.
Is there a way to implement the counter without initializing i?
According to your question what I can understand is you want to use enumerate to get your result.
You can simply do as below:
def project(r):
for (i, char) in enumerate(r, 0):
print(ord(r[-i-1])-96+i)
project(str(input()).lower())
And the enumerate() method adds a counter to an iterable and returns it in a form of an enumerate object.
Syntax: enumerate(iterable, start)
Here 0 is the default value of start which you can give according to your requirement. For example, if you want your counter to start from 100, then you can do like enumerate(iterable, 100).
In the above code, I have used enumerate() function and initialized the counter from 0 and as you want to display from the last, I used -ve index to get the last item in a list.
And as I initialized the counter 0 so how can I get the items from last? For that, I subtract the index by -1 like r[-i-1]. So for the first iteration the i value becomes 0, so r[-i-1] becomes r[-0-1] which is r[-1] and on the second iteration, i becomes 1, so r[-i-1] becomes r[-1-1]which isr[-2]` which result second last item. Similarly it goes on.
For more information about enumeration, please check the below link so you can get a clear idea.
Python enumerate()
13. Enumerate
Dcoder14, actually I want to make my code a bit shorter. Even there is a way other than enumerate, but still thank you very much... I used your code, but I edited it a little bit to make it one line shorter...
This is my code:
def project(r):
for (i, char) in enumerate(r, 0):
print(str(ord(r[-i-1])-96+i))
project(str(input()).lower())
If you want to make it shorter, you can use the decrement char value since we can get an increment by subtracting the length of the string (input) with char in the for loop.
For example, this is my code:
def project(r):
for char in range(len(r),0,-1):
print(ord(r[char-1])-96+(len(r)-char))
project(str(input()).lower())

Cryptopals challenge 4 concern

i am not getting the desired results for Cryptopals challenge 4 set 1.
The concept of the program to check to see if any of these 300ish strings have been XORd by a single character. So with a brute force, my solution is take every string, XOR it with every character on the keyboard, and check to see if any of these results produce an english sentence. if not, then check the next string. Here is my code:
MY_DICT = {}
index = 0
my_plaintext = "Now that the party is jumping"
#fills the dictionary with hex strings from the txt file
with open("hexstrings.txt") as f:
my_list = f.readlines()
for x in my_list:
MY_DICT[index] = x.rstrip('\n')
index = index + 1
i=0
input() #this is just here to help me keep track of where i am when running it
#this loop fills possible_plaintext with all the possible 255 XORs of the i'th string
#of the dictionary that was previously filler from the txt file
for i in range(326):
possible_plaintexts = brute_force_singlechar_xor(MY_DICT[i])
print(possible_plaintexts)
if possible_plaintexts == my_plaintext: #line of concern
print("ya found it yay :) ")
Im sure that myBruteForce function works because it worked properly on the last problem where i XORd every possible char against a string. and i also know that the plaintext is the one provided bc i saw the solution. im just not sure why my program isnt recognizing that the plaintext is not in the dictionary.
(i am aware that using a scoring system to score every string to see if its close to english would be easier, but this is the way i chose to do it for now until i figure out how to get my scoring function to work /: )
How is your dictionary "possible_plaintexts" like when you print it?
Can you spot the solution in the printed text? How is it printed?
The decrypted string should also have a '\n' character.

AHK Remove every second char from variable

I need a code on AHK
I have a variable look like this:
CYOMYACHOAYJGUGRYYQNYB
I need to get this:
YMAHAJURYNB
I meen, i need every second char from a variable. Thank in advance
Var := "CYOMYACHOAYJGUGRYYQNYB"
Loop, Parse, Var ; retrieves each character from the variable, one at a time
{
If (Mod(A_Index, 2) = 0) ; If A_Index is even (the remainder after division by 2 is 0)
NewVar .= A_LoopField ; add the retrieved character to the new variable
}
MsgBox %NewVar%
This works for me. I am using bit wise to determine if the index of the array of letters, given to me by StrSplit(TestString), is even or odd as I loop through them. I used this forum post for the bitwise logic. Then I concatenate if the line is even. So if index&1=0 will be true when the number is even, thus giving me every other letter to concatenate into NewString with this line NewString=%NewString%%letter%. Feel free to uncomment out the message box lines by removing the ; to better see how the loop parses the array.
TestString := "ABCD"
word_array := StrSplit(TestString)
NewString:=""
For index, letter in word_array{
if index&1=0
{
;MsgBox, %letter% added
NewString=%NewString%%letter%
;Msgbox, %NewString%
}
}
MsgBox, %NewString%
As you don't specify any language, I'll answer in pseudocode:
set counter to 1
set result to empty string
for every char in string:
if counter is even:
append char to result
increment counter by 1
user3419297 beat me to it, but mine is even easier:
InputBox, x, What Variable?, Enter Variable:
loop, % StrLen(x)
If mod(A_Index,2)=0
y.=substr(x,A_Index,1)
msgbox %y%
Clipboard := y
You input the variable in a dialog, and the result is shown, and put in clipboard. Hth,
EDIT: I like the bitwise logic from Zack Tarr! Substitute for the "if" above:
If A_Index&1=0
The rest is the same.

lua string get Nth number

I am trying to find the Nth number in a string. Should i use string.find? If so, how? I know the arguments are the string to search and the pattern to find, but the 3rd argument (where to start) seems like it might just work.
the lua string tutorial i am looking at
thanks!
You'll want to create a function that splits your string into an array. Once you've done this, you'll be able to return whatever number position you're looking for.
function findnth(str, nth)
local array = {}
for i in string.gmatch(str, "%d+") do
table.insert(array, i)
end
return array[nth]
end
The function above works like so:
print(findnth("1 3 7 2 15 2", 4))
Returns:
2
Edit: Changed function to suit OP's specific needs.

Duplicates In a String

I need to write a function that takes a string and returns it with duplicate characters removed in Lua. What I need help with is...
Making a hash with letters and the counts
Making each letter equal to only one, deleting more than one occurrence
Converting hash into the new string with duplicates removed
A simple function/algorithm would be appreciated!
If you only need one instance of each character then you probably don't need to keep track of the counts; you can compare the input string against the same table you use to generate the output.
local function contains(tbl, val)
for k,v in pairs(tbl) do
if v == val then return true end
end
return false
end
local function uniq(str)
local out = {}
for s in str:gmatch(".") do
if not contains(out, s) then out[#out+1] = s end
end
return table.concat(out)
end
print( uniq("the quick brown fox jumps over the lazy dog") )
-- the quickbrownfxjmpsvlazydg
This will probably be slower than the function below for short strings, but it's generally best to avoid excessive string concatenation in Lua, for the reasons outlined here. If you're sure the output string will be fairly short, you can get rid of contains() and use this:
local function uniq(str)
local out = ""
for s in str:gmatch(".") do
if not out:find(s) then out = out .. s end
end
return out
end

Resources