I've been trying to find a way to remove a string from a table kind of like this:
myTable = {'string1', 'string2'}
table.remove(myTable, 'string1')
but I haven't been able to find anyway to do it. Can someone help?
As hjpotter92 said, table.remove expects the position you want removed and not the value so you will have to search. The function below searches for the position of value and uses table.remove to ensure that the table will remain a valid sequence.
function removeFirst(tbl, val)
for i, v in ipairs(tbl) do
if v == val then
return table.remove(tbl, i)
end
end
end
removeFirst(myTable, 'string1')
table.remove accepts the position of an element as its second argument. If you're sure that string1 appears at the first index/position; you can use:
table.remove(myTable, 1)
alternatively, you have to use a loop:
for k, v in pairs(myTable) do -- ipairs can also be used instead of pairs
if v == 'string1' then
myTable[k] = nil
break
end
end
Related
local str = ",23,4"
local t = {}
local i = 1
for temp in str:gmatch("[^,]+") do
t[i] = temp
i = i + 1
end
I'm a Lua newbie. Here is my code. I expected that t[1] has nil. However, gmatch() skipped it instead of returning nil. Tabel t[] has only two key-values. If I make table t[] like this
t[1] = nil
t[2] = 23
t[3] = 4
, how do I use gmatch()? Or what function do I have to use?
gmatch() didn't skip anything; it did exactly what you told it to: it found every occurrance of "[^,]+", of which there are two, and handed each of them to the loop body.
If you want to match empty strings as well, you can change your pattern to "[^,]*".
+ matches one or more
* matches zero or more
Please refer to https://www.lua.org/manual/5.3/manual.html#6.4.1
when I run this codes the output is (" "," "),however it should be ("I","love")!!!, and there is no errors . what should I do to fix it ??
sen="I love dogs"
function Longest_word(sen)
x=" "
maxw=" "
minw=" "
minl=1
maxl=length(sen)
p=0
for i=1:length(sen)
if(sen[i]!=" ")
x=[x[1]...,sen[i]...]
else
p=length(x)
if p<min1
minl=p
minw=x
end
if p>maxl
maxl=p
maxw=x
end
x=" "
end
end
return minw,maxw
end
As #David mentioned, another and may be better solution can be achieved by using split function:
function longest_word(sentence)
sp=split(sentence)
len=map(length,sp)
return (sp[indmin(len)],sp[indmax(len)])
end
The idea of your code is good, but there are a few mistakes.
You can see what's going wrong by debugging a bit. The easiest way to do this is with #show, which prints out the value of variables. When code doesn't work like you expect, this is the first thing to do -- just ask it what it's doing by printing everything out!
E.g. if you put
if(sen[i]!=" ")
x=[x[1]...,sen[i]...]
#show x
and run the function with
Longest_word("I love dogs")
you will see that it is not doing what you want it to do, which (I believe) is add the ith letter to the string x.
Note that the ith letter accessed like sen[i] is a character not a string.
You can try converting it to a string with
string(sen[i])
but this gives a Unicode string, not an ASCII string, in recent versions of Julia.
In fact, it would be better not to iterate over the string using
for i in 1:length(sen)
but iterate over the characters in the string (which will also work if the string is Unicode):
for c in sen
Then you can initialise the string x as
x = UTF8String("")
and update it with
x = string(x, c)
Try out some of these possibilities and see if they help.
Also, you have maxl and minl defined wrong initially -- they should be the other way round. Also, the names of the variables are not very helpful for understanding what should happen. And the strings should be initialised to empty strings, "", not a string with a space, " ".
#daycaster is correct that there seems to be a min1 that should be minl.
However, in fact there is an easier way to solve the problem, using the split function, which divides a string into words.
Let us know if you still have a problem.
Here is a working version following your idea:
function longest_word(sentence)
x = UTF8String("")
maxw = ""
minw = ""
maxl = 0 # counterintuitive! start the "wrong" way round
minl = length(sentence)
for i in 1:length(sentence) # or: for c in sentence
if sentence[i] != ' ' # or: if c != ' '
x = string(x, sentence[i]) # or: x = string(x, c)
else
p = length(x)
if p < minl
minl = p
minw = x
end
if p > maxl
maxl = p
maxw = x
end
x = ""
end
end
return minw, maxw
end
Note that this function does not work if the longest word is at the end of the string. How could you modify it for this case?
I get strings in the following format:
abc:321,cba:doodoo,hello:world,eat:mysh0rts
I'd like to grab one instance of the data pairing from the string and remove it from the string, so for example if I wanted to grab the value following hello:world I'd like this to happen:
local helloValue, remainingString = GetValue("hello")
Which will return world for hellovalue and abc:321,cba:doodoo,eat:mysh0rts for remainingString.
I'm doing this rather cumbersomely with loops, what would a better way of doing it be?
This is one way:
local str = 'abc:321,cba:doodoo,hello:world,eat:mysh0rts'
local t = {}
for k, v in str:gmatch('(%w+):(%w+)') do
if k ~= 'hello' then
table.insert(t, k .. ':' .. v)
else
helloValue = v
end
end
remainingString = table.concat(t, ',')
print(helloValue, remainingString)
You can turn this to a more general GetValue function yourself.
Try also this:
local str = 'abc:321,cba:doodoo,hello:world,eat:mysh0rts'
function GetValue(s,k)
local p=k..":([^,]+),?"
local a=s:match(p)
local b=s:gsub(p,"")
return a,b
end
print(GetValue(str,"hello"))
print(GetValue(str,"eat"))
If you want to parse the whole string into key-value pairs, try this:
for k,v in str:gmatch("(.-):([^,]+),?") do
print(k,v)
end
(hello:[^,]+,)
Just do a replace with empty string.The replace data and $1 are the things you want.See demo.
http://regex101.com/r/yR3mM3/24
I have two parameters, both strings, and I need to find the index of where the second string is found within the first string. I can do this when it's just one character but not when its more. Here is an example of the one I can do:
for i, j in enumerate(primary):
if final == j:
index = i
break
This is what I tried for the problem:
for i in range (0,len(initial),1):
for j in range (len(initial), i, -1):
if initial[i:j] == last:
index_str = i
break
However, it always returns "None" so can anyone help me with this?
I think that you need the index() method. Example usage (taken from this link)
str1 = "this is string example....wow!!!";
str2 = "exam";
print str1.index(str2);
The string.find method can do that.
"somestring".find("str")
http://docs.python.org/2/library/string.html#string.find
I understand that str = str.replace('x', '') will eliminate all the x's.
But let's say I have a string jxjrxxtzxz and I only want to delete the first and last x making the string jjrxxtzz. This is not string specific. I want to be able to handle all strings, and not just that specific example.
edit: assume that x is the only letter I want to remove. Thank you!
One fairly straight forward way is to just use find and rfind to locate the characters to remove;
s = 'jxjrxxtzxz'
# Remove first occurrence of 'x'
ix = s.find('x')
if ix > -1:
s = s[:ix]+s[ix+1:]
# Remove last occurrence of 'x'
ix = s.rfind('x')
if ix > -1:
s = s[:ix]+s[ix+1:]
Not pretty but this will work:
def remove_first_last(c, s):
return s.replace(c,'', 1)[::-1].replace(c,'',1)[::-1]
Usage:
In [1]: remove_first_last('x', 'jxjrxxtzxz')
Out[1]: 'jjrxxtzz'