Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
649 views
in Technique[技术] by (71.8m points)

c - Convert const char to lowercase within hash fuction

I need to produce a hash value for a given word. the hash value need to be deterministic, or the same value for the same word, however if the given word has an different cases the hash value changes. So my objective is to convert the given word (const char) to a lower case witin the hash function, in order to obtain always the same hash code regardless the case. I have the following code:

#include <stdio.h>
#include <ctype.h>
#define LENGTH 45
const unsigned int N = 7703;

// Prototypes 
unsigned int hash(const char *word);

int main()
{
    int s;
    char *text;
    text = "aardvark's";    //given word this can have upper and lower cases
    s = hash(text);
    printf("text: %s
",text);
    printf("hash or text: %d
",s);

    return 0;
}


unsigned int hash(const char *word)      // the given word is constant char
{
   unsigned long h;
   unsigned char *str = (char*)word;

    h = 0;
    while(*str != '')
    {
       *str = tolower(*str);       //trying to convert to lower cases
       h = (h * LENGTH + *str) % N;
       str++;
    }
    return h;
}

I have tried the above as well as different combinations, but i keep getting errors, the main error is 'segmentation fault core dumped', but using different code arrangement i get error: 'makes pointer from integer without a cast'. Can you please advise how to resolve this? as I am stuck, many thanks.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You won't need to modify the original string when calculating hash.

Instead of trying to modify the original string, just use the conversion result in calculation without writing it back to the original string.

unsigned int hash(const char *word)      // the given word is constant char
{
    unsigned long h;

    h = 0;
    while(*word != '')
    {
       unsigned char c = tolower(*word);       //trying to convert to lower cases
       h = (h * LENGTH + c) % N;
       word++;
    }
    return h;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...