#compare 2 strings

1 messages · Page 1 of 1 (latest)

compact bluff
#

How would i compare two strings ([]const u8) to see if they have the identical value? In C there is a strcmp function. Would i do this differently in ZIG, or do i need to implement my own strcmp function which just itterates over the string's bytes?

delicate gyro
#

std.mem.eql

compact bluff
#

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)

boreal raven
#

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(...)) ...

compact bluff
dawn storm
boreal raven
dawn storm
#

Colors and everything

boreal raven
#

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)

dawn storm
#

Cool thanks

humble rover
#

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);
}
boreal raven
#

(excluding null character)

#

So where you usually couldn't have a space in an identifier, you can by writing @"foo bar"

humble rover
latent locust
#

if ur comparing them more than once it'd be a good idea to hash the strings and then compare the hashes

#

its much faster