#include <stdio.h>
#include <stdlib.h>
#include <wchar.h>
#include <locale.h>
#include <string.h>
#include <iconv.h>
char8_t* convert_wchar_to_utf8(const wchar_t* wstr) {
size_t len = wcslen(wstr);
size_t buf_size = len * 4 + 1; // UTF-8 can use up to 4 bytes per wchar_t
char8_t* u8str = (char8_t*)malloc(buf_size);
if (!u8str) return NULL;
// Convert wide string to UTF-8
size_t converted = wcstombs((char*)u8str, wstr, buf_size);
if (converted == (size_t)-1) {
free(u8str);
return NULL;
}
return u8str;
}
wchar_t* convert_utf8_to_wchar(const char8_t* u8str) {
mbstate_t state = {0};
size_t len = strlen((const char*)u8str);
size_t buf_size = len + 1; // Enough to hold the wide string
wchar_t* wstr = (wchar_t*)malloc(buf_size * sizeof(wchar_t));
if (!wstr) return NULL;
size_t converted = mbstowcs(wstr, (const char*)u8str, buf_size);
if (converted == (size_t)-1) {
free(wstr);
return NULL;
}
return wstr;
}
void extract_substring(const wchar_t* wstr, size_t start, size_t length, wchar_t* result) {
wcsncpy(result, wstr + start, length);
result[length] = L'\0'; // Null terminate the substring
}
int main() {
// Set the locale to the user's default
setlocale(LC_ALL, "");
const char8_t* utf8_string = (const char8_t*)"Hello, world!";
// Step 1: Convert char8_t* to wchar_t*
wchar_t* wide_string = convert_utf8_to_wchar(utf8_string);
if (!wide_string) {
fprintf(stderr, "UTF-8 to wchar_t conversion failed\n");
return 1;
}
// Step 2: Extract a substring (from position 7 with length 5)
size_t start = 7; // "world"
size_t length = 5; // Length of "world"
wchar_t* substring = (wchar_t*)malloc((length + 1) * sizeof(wchar_t)); // +1 for null termination
if (!substring) {
free(wide_string);
fprintf(stderr, "Memory allocation failed for substring\n");
return 1;
}
extract_substring(wide_string, start, length, substring);
// Step 3: Convert wchar_t* back to char8_t*
char8_t* u8_substring = convert_wchar_to_utf8(substring);
if (!u8_substring) {
free(wide_string);
free(substring);
fprintf(stderr, "wchar_t to UTF-8 conversion failed\n");
return 1;
}
// Print results
printf("Original string (UTF-8): %s\n", (const char*)utf8_string);
printf("Substring (UTF-8): %s\n", (const char*)u8_substring);
// Clean up
free(wide_string);
free(substring);
free(u8_substring);
return 0;
}