Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying string with russian symbols in c language

Tags:

arrays

c

string

I have code:

#include <stdio.h>

int main() {
  char abc[] = "Hello";
  abc[0] = 'm';
  printf("%s\n", abc);
  return 0;
}

It prints 'mello' and everything works correctly.

I have another code:

#include <stdio.h>

int main() {
  char abc[] = "Привет";
  abc[0] = 'm';
  printf("%s\n", abc);
  return 0;
}

It prints 'm?ривет'. Whats wrong with russian symbols?

like image 482
undefined7887 Avatar asked Sep 02 '25 05:09

undefined7887


1 Answers

Russian letters are encoded in UTF-8 on your system. They use 2 bytes for each Cyrillic letter. You cannot change letters by changing individual char elements in the strings, you must construct new strings from substrings.

Here is a program to illustrate how the encoding works:

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

int utf8_length(const char *s) {
    if (*s < 128)
        return 1;   // regular ASCII byte
    if (*s < 128+64)
        return -1;  // continuation byte, invalid code point
    if (*s < 128+64+32)
        return 2;   // code-point encoded on 2 bytes
    if (*s < 128+64+32+16)
        return 3;   // code-point encoded on 3 bytes
    if (*s < 128+64+32+16+8)
        return 4;   // code-point encoded on 4 bytes
    return -1;      // invalid code point
}

void test(const char *s) {
    int len = strlen(s);
    int i, nbytes;

    printf("Hex representation of %s:\n", s);
    for (i = 0; i <= len; i++) {
        printf("%02X ", (unsigned char)s[i]);
    }
    printf("\n");
    for (i = 0; i < len; i += nbytes) {
        nbytes = utf8_length(s + i);
        if (nbytes < 0) {
            printf("invalid encoding at %d\n", i);
        } else {
            printf("%*s%.*s ",
                   nbytes * 3 - 2 - (nbytes > 2), "",
                   nbytes, s + i);
        }
    }
    printf("\n\n");
}

int main() {
    char buf[128];
    char abc[] = "Привет";

    test("hello");  // English
    test(abc);      // Russian
    test("你好");   // Mandarin

    strcpy(buf, "m");
    strcat(buf, abc + utf8_length(abc));

    printf("modified string: %s\n", buf);
    test(buf);

    return 0;
}

Output:

Hex representation of hello:
68 65 6C 6C 6F 00
 h  e  l  l  o

Hex representation of Привет:
D0 9F D1 80 D0 B8 D0 B2 D0 B5 D1 82 00
    П     р     и     в     е     т

Hex representation of 你好:
E4 BD A0 E5 A5 BD 00
      你       好

modified string: mривет
Hex representation of mривет:
6D D1 80 D0 B8 D0 B2 D0 B5 D1 82 00
 m     р     и     в     е     т
like image 184
chqrlie Avatar answered Sep 04 '25 18:09

chqrlie