#compare 2 strings
1 messages · Page 1 of 1 (latest)
std.mem.eql
When mapping strings to different values for example should i use this method? Something like hashmaps would sound better (in performance) in this case, however i have never worked with them before and don't really know about their performances.
"A string" -> 0,
"B string" -> 1,
"C string" -> 2,
....
(The actual strings may vary, the resulting integers would stay roughly the same)
my usual recommendation for branching on a string, where the string comparisons are known beforehand, is to use std.meta.stringToEnum like so:
const Case = enum {
@"A string",
@"B string",
@"C string",
};
const case = std.meta.stringToEnum(Case, str) orelse .@"A string"; // or handle this in some other way
const value: u8 = switch (case) {
.@"A string" => 0,
.@"B string" => 1,
.@"C string" => 2,
};
_ = value;
it uses std.ComptimeStringMap under the hood for enums with less than a certain number of members (something like 100), so the performance is about equivalent if not better to using a normal runtime hash map
if the branches are not known beforehand, then you'll have to rely on a normal hashmap, like std.StringHashMap, or otherwise just make a chain of if (std.mem.eql(...)) else if (std.mem.eql(...)) ...
This is probably perfect since i planned on converting the ints to enum values anyways. Thank you
How did you format that codeblock so neatly?
wdym?
Colors and everything
you just append the abbreviated name of some language like rs or ts after the first three backticks
(zig isn't supported unfortunately, but I've found ts and rs often work well enough)
Cool thanks
You can use std.mem.eql
I usually write this utility function
/// Compares two strings. Returns a bool based on their equality.
fn streql(original: []const u8, compto: []const u8) bool {
return std.mem.eql(u8, original, compto);
}
What does the @ prefix do?
@"" syntax allows you to use any arbitrary unicode as an identifier
(excluding null character)
So where you usually couldn't have a space in an identifier, you can by writing @"foo bar"
Oh, gotcha! I didn't know that. I'll have to throw it up on the magazine