代码之家  ›  专栏  ›  技术社区  ›  Stove Games Games

如何向string/char数组添加空格字符?

c
  •  0
  • Stove Games Games  · 技术社区  · 5 年前

    以下是概述: 如何将空格添加到字符串-char输出[]~~~~~~~~这就是字符串

    for(int j = 0; input[j] != '\0'; j++){
        int at_index = 0;
        int i = 0;
    
        //need to check at this point for whitespace
        if(input[j] == ' '){
            output[j] = ' ';
        }
        //gives garbage value
    
        for(i; alphabet[i] != input[j]; i++){
            ++at_index;
        }
    
        output[j] = alphabet[at_index + shift];
    
    }
    
    1 回复  |  直到 5 年前
        1
  •  0
  •   the busybee    5 年前

    您所犯的错误是在识别出空格后没有停止对字符的处理。

    这是一种可能的解决方案,来源于您的来源:

    for (int j = 0; input[j] != '\0'; j++) {
        if (isspace(input[j])) {
            output[j] = input[j];
    
        } else {
            for (int i = 0; alphabet[i] != input[j]; i++) {
            }
            output[j] = alphabet[i + shift];
        }
    }
    

    注意事项:

    • at_index i
    • 如果输入字符不在 alphabet . 因为我不知道你 字母表
    • for
    • 你需要一些逻辑来防止越界访问 字母表 当读取移位字符时。
        2
  •  0
  •   Frostmourne    5 年前

    我会调用一个helper函数来实现这一点,

    white_spaces(char *dest, int size, int num_of_spaces) {
        int len = strlen(dest);
        // for the check i still assume dest tto contain a valid '\0' terminated string, so len will be smaller than size
        if( len + num_of_spaces >= size ) {
            num_of_spaces = size - len - 1;
        }  
        memset( dest+len, ' ', num_of_spaces );   
        dest[len + num_of_spaces] = '\0';
    }