I am trying to find if some string is really in list. There is my code:
comparing() ->
FileName = "msg-0001",
{ok,[NumLine],_} = io_lib:fread("msg-~d",FileName),
io:format("Numline:~p~n", [NumLine]),
{ok, Pars} = file:read_file("parsing.txt"),
{ok, Dump} = file:read_file("msg-0001"),
StringNumline = lists:flatten(io_lib:format("~p", [NumLine])),
io:format("StringNumline:~p~n", [StringNumline]),
StringDump = lists:flatten(io_lib:format("~p", [Dump])),
io:format("StringDump:~p~n", [StringDump]),
SubStringDump = string:substr(StringDump, 4),
io:format("SubStringDump:~p~n", [SubStringDump]),
Ndump = concat(StringNumline, SubStringDump),
io:format("Ndump:~p~n", [Ndump]),
FineDump = Ndump--"\">>",
io:format("FineDump:~p~n", [FineDump]),
L1 = binary:split(Pars, <<"\r\n">>, [global]),
io:format("L1=~p~n", [L1]),
Check = lists:member(FineDump, L1),
io:format("Check=~p~n", [Check]),
if
Check ->
file:write_file("check.txt", "true\n", [append]);
true ->
file:write_file("check.txt", "false\n", [append])
end.
Here is output of the code:
10> c(compare).
{ok,compare}
11> compare:comparing().
Numline:1
StringNumline:"1"
StringDump:"<<\"hello\">>"
SubStringDump:"hello\">>"
Ndump:"1hello\">>"
FineDump:"1hello"
L1=[<<"0hello">>,<<"something">>,<<"anyword">>,<<"1hello">>,<<"2exercise">>,
<<"2solution">>,<<"3test">>,<<"new">>,<<"4check">>,<<"4grade">>]
Check=false
ok
I have a problem in line Check = lists:member(FineDump, L1). It's always false although 1hello is member of the list. I don't know where is the mistake. Is it function lists:member fine for this operation? Or does exist some other way to find if string is a member of a list? I'm new at Erlang.
L1 is a list of binaries while FineDump is a string (a list of integers in Erlang). You need to convert FineDump into a binary to make the lists:member/2 call work.
This should work:
Check = lists:member(list_to_binary(FineDump), L1),
You also seem to be doing this in a way too convoluted way than necessary. If I understood the logic fine, you don't need all that code. You can concatenate NumLine and Dump into a binary using just:
X = <<(integer_to_binary(NumLine))/binary, Dump/binary>>
and then use that directly in lists:member:
lists:member(X, L1)
1> NumLine = 1.
1
2> Dump = <<"hello">>.
<<"hello">>
3> <<(integer_to_binary(NumLine))/binary, Dump/binary>>.
<<"1hello">>
Related
How have Nim to convert string to int the simplest native way without a coder put import std...
so on ?
var
s = "99"
si :int
i = 1
si = s ... # <- ? picturing
i += si # <- - " - must finely be 100
import std/strutils
var
s = "99"
i = 0
s_int = parseInt(s)
i += s_int
I'm not sure why you don't want to import a standard library module (std/strutils), but if you don't want to do that, you'll have to implement the equivalent of parseInt yourself.
Well, the only things you are requiring are that there are no imports used and that this is conversion is the simplest possible with the final result being 100, right? Essentially you don't care about:
should your conversion handle negative numbers?
should your conversion handle overflow, and how (return value/exception/other)?
should your conversion ignore invalid input silently?
should your conversion allow different inputs (non 99)?
should your conversion stop parsing at the first number or continue to extract all possible numbers?
This should fit the bill:
var
s = "99"
si :int
i = 1
proc simplest_string_to_int(input: string): int = 99
si = simplest_string_to_int(s)
i += si # <- - " - must finely be 100
echo i
Or alternatively, go look at the implementation of string parsing you don't want to import and copy&paste that into your code, so you don't have to import it.
https://play.nim-lang.org/#ix=3Xlq
proc toInt(s: string): int =
for c in s:
result = result * 10 + c.int - '0'.int
How can I add a method to the string table and modify self inside it ?
Basically, I'm trying to mimic the behaviour of the io.StringIO.read method in python, which reads n char in the string and returns them, modifying the string by "consuming" it.
I tried this:
function string.read(str, n)
to_return = str:sub(1, n)
str = str:sub(n + 1)
return to_return
end
local foo = "heyfoobarhello"
print(string.read(foo, 3))
print(foo)
Output is:
hey
heyfoobarhello
I expected the second line to be only foobarhello.
How can I achieve this ?
To mimic Python's io.StringIO class, you must make an object that stores both the underlying string and the current position within that string. Reading from an IO stream normally does not modify the underlying data.
local StringIO_mt = {
read = function(self, n)
n = n or #self.buffer - self.position + 1
local result = self.buffer:sub(self.position, self.position + n - 1)
self.position = self.position + n
return result
end,
}
StringIO_mt.__index = StringIO_mt
local function StringIO(buffer)
local o = {buffer = buffer, position = 1}
setmetatable(o, StringIO_mt)
return o
end
local foo = StringIO"heyfoobarhello"
print(foo:read(3))
print(foo:read())
Output:
hey
foobarhello
I don't recommend adding this class or method to Lua's string library, because the object has to be more complex than just a string.
You can add methods to the datatype string independently from the string table.
Short example that shows that the string methods even work if string table gets deleted...
string=nil
return _VERSION:upper():sub(1,3)
-- Returning: LUA
So you can add a method...
-- read.lua
local read = function(self, n1, n2)
return self:sub(n1, n2)
end
getmetatable(_VERSION).__index.read=read
return read
...for all strings.
( Not only _VERSION )
And use it...
do require('read') print(_VERSION:read(1,3):upper()) end
-- Print out: LUA
I need to parse Integer from first String position.
Something like this:
String s = "1abc";
int x = s.charAt(0);
This doesn't work (obviously) but hopefully you got the idea.
I also can't use anything like this:
int x = s.substring(0, 1);
Since that would return second character ('a') in this case.
For java you could do
int x = Integer.parseInt(s.substring(0,1));
Check if it works
I'm searching a Textpad syntax file for groovy. There is none on the Textpad Syntax Definitions page (http://www.textpad.com/add-ons/syna2g.html).
All I have found so far are links to a file that was on Codehaus (http://docs.codehaus.org/download/attachments/2747/groovy.syn). Now that Codehaus is gone, where do I find that file? Anybody still has it installed and can post it here?
It's in the internet archive:
https://web.archive.org/web/20150508150805/http://docs.codehaus.org/download/attachments/2747/groovy.syn
I'll post it here as well -- though at time of writing, it's 3 years old, and probably needs updating ;-)
; (c) July 2004, Guillaume Laforge
; Groovy, a scripting language for the JVM, is hosted at Codehaus
; This file is a Groovy Syntax for TextPad,
; inspired from the Java Syntax file provided with TextPad
C=1
[Syntax]
Namespace1 = 6
IgnoreCase = No
InitKeyWordChars = A-Za-z_
KeyWordChars = A-Za-z0-9_
BracketChars = {[()]}
OperatorChars = -+*/<>!~%^&|=.
PreprocStart =
SyntaxStart =
SyntaxEnd =
HexPrefix = 0x
CommentStart = /*
CommentEnd = */
CommentStartAlt = """
CommentEndAlt = """
SingleComment = //
SingleCommentCol =
SingleCommentAlt =
SingleCommentColAlt =
SingleCommentEsc =
StringsSpanLines = Yes
StringStart = "
StringEnd = "
StringAlt =
StringEsc = \
CharStart = '
CharEnd = '
CharEsc = \
[Keywords 1]
; Keywords and common classes
as
assert
Boolean
Byte
Character
Class
Double
Float
Integer
Long
Number
Object
Short
String
property
void
abstract
assert
boolean
break
byte
case
catch
char
class
const
continue
default
do
double
else
extends
false
final
finally
float
for
goto
if
implements
import
instanceof
in
int
interface
long
native
new
null
package
private
protected
public
return
short
static
strictfp
super
switch
synchronized
this
throw
throws
transient
true
try
void
volatile
while
[Keywords 2]
abs
accept
allProperties
and
any
append
asImmutable
asSynchronized
asWritable
center
collect
compareTo
contains
count
decodeBase64
div
dump
each
eachByte
eachFile
eachFileRecurse
eachLine
eachMatch
eachProperty
eachPropertyName
eachWithIndex
encodeBase64
every
execute
filterLine
find
findAll
findIndexOf
flatten
getErr
getIn
getOut
getText
inject
inspect
intersect
intdiv
invokeMethod
isCase
join
leftShift
max
min
minus
mod
multiply
negate
newInputStream
newOutputStream
newPrintWriter
newReader
newWriter
next
or
padLeft
padRight
plus
pop
previous
print
println
readBytes
readLine
readLines
reverse
reverseEach
rightShift
rightShiftUnsigned
round
size
sort
splitEachLine
step
subMap
times
toDouble
toFloat
toInteger
tokenize
toList
toLong
toURL
transformChar
transformLine
upto
use
waitForOrKill
withInputStream
withOutputStream
withPrintWriter
withReader
withStream
withStreams
withWriter
withWriterAppend
write
writeLine
I want to read a line from a file, initialize an array from that line and then display the integers.
Why is is not reading the five integers in the line? I want to get output 1 2 3 4 5, i have 1 1 1 1 1
open Array;;
open Scanf;;
let print_ints file_name =
let file = open_in file_name in
let s = input_line(file) in
let n = ref 5 in
let arr = Array.init !n (fun i -> if i < !n then sscanf s "%d" (fun a -> a) else 0) in
let i = ref 0 in
while !i < !n do
print_int (Array.get arr !i);
print_string " ";
i := !i + 1;
done;;
print_ints "string_ints.txt";;
My file is just: 1 2 3 4 5
You might want to try the following approach. Split your string into a list of substrings representing numbers. This answer describes one way of doing so. Then use the resulting function in your print_ints function.
let ints_of_string s =
List.map int_of_string (Str.split (Str.regexp " +") s)
let print_ints file_name =
let file = open_in file_name in
let s = input_line file in
let ints = ints_of_string s in
List.iter (fun i -> print_int i; print_char ' ') ints;
close_in file
let _ = print_ints "string_ints.txt"
When compiling, pass str.cma or str.cmxa as an argument (see this answer for details on compilation):
$ ocamlc str.cma print_ints.ml
Another alternative would be using the Scanf.bscanf function -- this question, contains an example (use with caution).
The Scanf.sscanf function may not be particularly suitable for this task.
An excerpt from the OCaml manual:
the scanf facility is not intended for heavy duty lexical analysis and parsing. If it appears not expressive enough for your needs, several alternative exists: regular expressions (module Str), stream parsers, ocamllex-generated lexers, ocamlyacc-generated parsers
There is though a way to parse a string of ints using Scanf.sscanf (which I wouldn't recommend):
let rec int_list_of_string s =
try
Scanf.sscanf s
"%d %[0-9-+ ]"
(fun n rest_str -> n :: int_list_of_string rest_str)
with
| End_of_file | Scanf.Scan_failure _ -> []
The trick here is to represent the input string s as a part which is going to be parsed into a an integer (%d) and the rest of the string using the range format: %[0-9-+ ]", which will match the rest of the string, containing only decimal digits 0-9, the - and + signs, and whitespace .