小编Kis*_*B87的帖子

C 中字符串的哈希函数

我目前正在尝试用 C 语言为我的程序实现哈希函数。我找到了许多可能的解决方案,但我不理解它们。下面是哈希函数:

int hash(const char *word) {
    int hash = 0;
    int n;
    for (int i = 0; word[i] != '\0'; i++) {
        // alphabet case
        if (isalpha(word[i]))
            n = word[i] - 'a' + 1;
        else  // comma case
            n = 27;

        hash = ((hash << 3) + n) % SIZE;
    }
    return hash;
}
Run Code Online (Sandbox Code Playgroud)

我们为什么要从'a'+1中减去word[i]?另外,我们为什么要做以下事情:hash = ((hash << 3) + n) % SIZE

c hash hashcode

5
推荐指数
1
解决办法
2万
查看次数

将字典传递给python中的字符串

我正在尝试使用键值对格式化字符串,其中字符串中的变量修饰符由键的名称引用.

我该怎么做?这是我的代码:

given_string2 = "I'm %(name)s. My real name is %(nickname)s, but my friends call me %(name)s."
def sub_m(name, nickname):
    return given_string2 %{name:nickname}
print sub_m("Mike","Goose")
Run Code Online (Sandbox Code Playgroud)

python string dictionary

3
推荐指数
1
解决办法
128
查看次数

如何在Python中进行HTML转义?

我正在尝试实现一个替换以下值的函数:

# > with &gt;
# < with &lt;
# " with &quot;
# & with &amp
Run Code Online (Sandbox Code Playgroud)

我的功能一直出错.究竟出了什么问题?

def escape_html(s):
    data = list(s)
    if ">" in data:
        data.replace(">","&gt;") 
    if "<" in data:
        data.replace("<","&lt;") 
    if '"' in data:
        data.replace('"',"&quot;") 
    if "&" in data:
        data.replace("&","&amp;") 
    word = data.join()
    return word

print escape_html("<>")
Run Code Online (Sandbox Code Playgroud)

注意:这更像是一个基本的编程问题.我的重点是我的功能不起作用的原因.我不能在这个项目中使用外部库.

python string

1
推荐指数
1
解决办法
1597
查看次数

python中是否需要字符串初始化?

鉴于此代码:

  def double_char(str):
  result = ""
  for i in range(len(str)):
    result += str[i] + str[i]
  return result
Run Code Online (Sandbox Code Playgroud)

result = ""字符串的初始化?如果是这样,有必要在第一时间做吗?

python string

1
推荐指数
1
解决办法
107
查看次数

如何通过从C中的函数传递指针来修复分段错误?

GDB告诉我第52行导致了分段错误.我不明白为什么.我正在实现一个简单的堆栈.它有两个功能:pop和push.看来pop不起作用.pop的目的是检索堆栈上的最高值.但是,当它试图这样做时,我得到一个分段错误.有谁知道原因?

/*************************************************************************
 * stack.c
 *
 * Implements a simple stack structure for char* s.
 ************************************************************************/

// for strdup() in the testing code
#define _XOPEN_SOURCE 500

#include <assert.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// the capacity of the stack
#define CAPACITY 10

//global variable used to keep track of pop and push


typedef struct
{
    // storage for the elements in the stack
    char* strings[CAPACITY];

    // the number of elements currently in the stack
    int size;
}stack;

// …
Run Code Online (Sandbox Code Playgroud)

c string pointers segmentation-fault

0
推荐指数
1
解决办法
142
查看次数

标签 统计

string ×4

python ×3

c ×2

dictionary ×1

hash ×1

hashcode ×1

pointers ×1

segmentation-fault ×1