iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🐕

Displaying Hiragana Substrings in C

に公開

By changing the printf formatter to %.*s, you can display a string of a specified size starting from the beginning. In the case of Hiragana, one character is 3 bytes, so you need to specify 9 bytes to extract 3 characters.

#include <stdio.h>
#include <stdint.h>

int main(void){
    uint8_t *str = "あいうえお";

    // A-I-U (あいう)
    printf("%.*s\n", 9, str);

    // E-O (えお)
    printf("%s\n", str+9);

    // A-I-U-E-O (あいうえお)
    printf("%s\n", str);

    str += 9;

    // E-O (えお)
    printf("%s\n", str);

    str -= 9;

    // A-I-U-E-O (あいうえお)
    printf("%s\n", str);

    return 0;
}

Next, I will show a method to copy and display a substring using strndup (POSIX standard, C23). This way, you don't have to worry about the destination memory capacity or the trailing null character.

#include<stdio.h>
#include <stdint.h>
#include<string.h>

int main()
{
    uint8_t* src = "あいうえお";

    // A-I-U (あいう)
    uint8_t* dest = strndup(src, 9);
    printf("%s\n", dest);

   // E-O (えお)
    dest = strndup(src+9, 6);
    printf("%s\n", dest);

    return 0;
}

When using strncpy, the trailing null character is not guaranteed, so you need to insert it yourself.

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>

int main()
{
    uint8_t* src = "あいうえお";
    uint8_t* dest;

    // A-I-U (あいう)
    dest = malloc(9 + 1);
    strncpy((char*) dest, (char*) src, 9);
    dest[9] = 0;
    printf("%s\n", dest);

    // E-O (えお)
    strncpy((char*) dest, (char*) src+9, 6);
    dest[6] = 0;
    printf("%s\n", dest);

    // A-I-U-E-O (あいうえお)
    dest = realloc(dest, 15+1);
    strncpy((char*) dest, (char*) src, 15);
    dest[15] = 0;
    printf("%s\n", dest);

    return 0;
}

Discussion