改变字符串的长度(为字符分配内存)
Changing the length of a string (allocating memory for characters)
def get_avail_mb(): int
f: FILE = FILE.open("/proc/meminfo","r")
s: string = ""
while s.length < 200 do s += " "
f.read(s, 200, 1)
var a = s.split("\n")
s = a[2]
t: string = ""
for var i = 0 to s.length
if s[i] <= '9' && s[i] >= '0'
t += s[i].to_string()
return int.parse(t)/1000
请注意我如何使用 while s.length < 200 do s += " "
将字符串分配给 200 个字符,以便从文件中将字节读入该字符串?除了追加 space 个字符 N 次之外,是否有更好的方法在 Genie 中将字符串的长度设置为 N 个字符?
可能最好的方法是创建一个固定大小的数组作为缓冲区并将缓冲区转换为字符串。这避免了编译时出现一些 C 警告。编译 valac --pkg posix example.gs
:
[indent=4]
uses
Posix
init
print( @"Available memory: $(get_avail_mb()) MB" )
def get_avail_mb():int
f:FILE = FILE.open("/proc/meminfo","r")
buffer:uint8[200]
f.read(buffer, 200, 1)
result:int = 0
match_result:MatchInfo
if ( /^MemAvailable:\s*([0-9]*).*$/m.match(
(string)buffer,
0,
out match_result
))
result = int.parse( match_result.fetch( 1 ))/1000
return result
或者您可以尝试 string.nfill ():
[indent=4]
uses
Posix
init
print( @"Available memory: $(get_avail_mb()) MB" )
def get_avail_mb():int
f:FILE = FILE.open("/proc/meminfo","r")
s:string = string.nfill( 200, ' ' )
f.read(s, 200, 1)
result:int = 0
match_result:MatchInfo
if ( /^MemAvailable:\s*([0-9]*).*$/m.match(
s,
0,
out match_result
))
result = int.parse( match_result.fetch( 1 ))/1000
return result
是的,只是避免无法处理某些极端情况的可怕的 for 循环!
def get_avail_mb(): int
f: FILE = FILE.open("/proc/meminfo","r")
s: string = ""
while s.length < 200 do s += " "
f.read(s, 200, 1)
var a = s.split("\n")
s = a[2]
t: string = ""
for var i = 0 to s.length
if s[i] <= '9' && s[i] >= '0'
t += s[i].to_string()
return int.parse(t)/1000
请注意我如何使用 while s.length < 200 do s += " "
将字符串分配给 200 个字符,以便从文件中将字节读入该字符串?除了追加 space 个字符 N 次之外,是否有更好的方法在 Genie 中将字符串的长度设置为 N 个字符?
可能最好的方法是创建一个固定大小的数组作为缓冲区并将缓冲区转换为字符串。这避免了编译时出现一些 C 警告。编译 valac --pkg posix example.gs
:
[indent=4]
uses
Posix
init
print( @"Available memory: $(get_avail_mb()) MB" )
def get_avail_mb():int
f:FILE = FILE.open("/proc/meminfo","r")
buffer:uint8[200]
f.read(buffer, 200, 1)
result:int = 0
match_result:MatchInfo
if ( /^MemAvailable:\s*([0-9]*).*$/m.match(
(string)buffer,
0,
out match_result
))
result = int.parse( match_result.fetch( 1 ))/1000
return result
或者您可以尝试 string.nfill ():
[indent=4]
uses
Posix
init
print( @"Available memory: $(get_avail_mb()) MB" )
def get_avail_mb():int
f:FILE = FILE.open("/proc/meminfo","r")
s:string = string.nfill( 200, ' ' )
f.read(s, 200, 1)
result:int = 0
match_result:MatchInfo
if ( /^MemAvailable:\s*([0-9]*).*$/m.match(
s,
0,
out match_result
))
result = int.parse( match_result.fetch( 1 ))/1000
return result
是的,只是避免无法处理某些极端情况的可怕的 for 循环!