可以使用以下代码实现包含中文字符串的居中换行:

#include <stdio.h>
#include <wchar.h>
#include <locale.h>

void printCenter(const wchar_t* str, int width) {
    int strLen = wcslen(str);
    int leftPadding = (width - strLen) / 2;
    int rightPadding = width - strLen - leftPadding;

    for (int i = 0; i < leftPadding; i++) {
        wprintf(L" ");
    }
    wprintf(L"%ls", str);
    for (int i = 0; i < rightPadding; i++) {
        wprintf(L" ");
    }
    wprintf(L"\n");
}

int main() {
    setlocale(LC_ALL, ""); // 设置本地化环境以支持宽字符输出

    const wchar_t* str1 = L"你好,世界!";
    const wchar_t* str2 = L"Hello, world!";
    int width = 20;

    printCenter(str1, width);
    printCenter(str2, width);

    return 0;
}

该程序通过printCenter函数实现了将字符串居中输出的功能。它首先计算左边和右边的填充空格数量,然后循环输出相应数量的空格和字符串,最后换行。在main函数中,我们可以调用printCenter函数来输出包含中文字符串的居中换行结果

用C语言实现包含中文字符串的居中换行

原文地址: https://www.cveoy.top/t/topic/hDzN 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录