c - 迭代具有非标准字符的 char 数组

标签 c arrays

编辑: 我只能使用 stdio.h 和 stdlib.h

我想遍历一个充满字符的字符数组。

但是,像 ä,ö 这样的字符会占用两倍的空间并使用两个元素。 这就是我的问题所在,我不知道如何访问那些特殊字符。

在我的示例中,字符“ä”将使用 hmm[0] 和 hmm[1]。

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

int main()
{
  char* hmm = "äö";

  printf("%c\n", hmm[0]); //i want to print "ä"

  printf("%i\n", strlen(hmm));

  return 0;
}

谢谢,我尝试在 Eclipse 中运行我附加的代码,它可以正常工作。我假设是因为它使用 64 位并且“ä”有足够的空间来容纳。 strlen 确认每个“ä”仅计为一个元素。 所以我想我可以以某种方式告诉它为每个字符分配更多空间(所以“ä”可以容纳)?

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

int main()
{
 char* hmm = "äüö";

  printf("%c\n", hmm[0]);
  printf("%c\n", hmm[1]);
  printf("%c\n", hmm[2]);

  return 0;
}

最佳答案

一个字符总是使用一个字节。

在您的情况下,您认为“ä”是一个字符:错误。 使用十六进制查看器打开您的 .c 源代码,您会看到 ä 使用了 2 个字符,因为该文件是用 UTF8 编码的

现在的问题是你想使用宽字符吗?

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

int main()
{
    const wchar_t hmm[] = L"äö";

    setlocale(LC_ALL, "");
    wprintf(L"%ls\n", hmm);
    wprintf(L"%lc\n", hmm[0]);
    wprintf(L"%i\n", wcslen(hmm));

    return 0;
}

关于c - 迭代具有非标准字符的 char 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14083706/

相关文章:

c - 如何在 C 编程中锁定文件并避免在写入时读取文件

c - MIPS 中的 lw(也有点 C)

c# - 如何在 SQL Server 中存储和检索 varbinary(max) 列

C++ : constructor initialization list for an array?

iOS swift : Array index out of range when accessing last property

php - Laravel 对象到数组

arrays - 验证数组内容 Mongoose 模型

c - 总是出现段错误

c - Linux 内核模块中 x87 内联汇编中的操作数类型不匹配

c - 满足基本条件后,程序不会终止递归循环