c - 将元素的第一个字符存储在字符串中

标签 c arrays string

<分区>

如何在字符串中存储元素的第一个字符?例如。如果我跑

for (j=0; j < 5; j++) {
    printf("%s\n, string[j]);
}

我明白了

hello
how
are
you

感谢@Holy semicolon 提供的答案,我知道我可以运行 printf("%c\n, string[j][0]); 来打印第一个字母:

h
h
a
y

但是,如何将首字母存储在新数组中? 到目前为止,我有:

char secondStr[10];

for (j=0; j<5; j++) {
    secondStr[j] = string[j][0];
}

这会导致错误assignment makes pointer from integer without a cast

我知道这个问题与我之前提出的问题(关于打印第一个元素)略有不同——我不确定是否要就 SO 提出一个全新的问题。如果我应该问一个新问题,我提前道歉。

最佳答案

当您有一个指向 char *string1[] = {"hello", "how", "are", "you"}; 的指针数组时; 并且您想打印第一个字符串它的 hello 所以你必须使用 %s 像这样的字符串 printf("%s",string1[0]) 但如果你想要要打印第一个字符串的第一个字符,您需要像这样使用 %c printf("%c",string1[0][0])

#include <stdio.h>

int main()
{
    char *string1[] = {"hello", "how", "are", "you"};
    printf("%s",string1[0][0]);  // I think you did this fault It'll give you Segmentation fault                                                                                                         


    return 0;
}

正如您在上面的代码中看到的,您需要将 %s 替换为 %c

编辑

What if I wanted to store the first letters in a new list?

然后您需要为新字符串分配内存。

#include <stdio.h>
#include <stdlib.h>
int main()
{
    char *string1[] = {"hello", "how", "are", "you"};
    char **keep = calloc(sizeof(char*),5);    //memory allocating

    for (int index = 0; index <= 3; index++)
    {
        keep[index] = calloc(sizeof(char),2);     //memory allocating
        keep[index][0] = string1[index][0];   
        keep[index][1] = '\0';      
    }

    //for test
    for (int i = 0; i <= 3; i++)
        printf("%c\n",keep[i][0]);

    return 0;
}

关于c - 将元素的第一个字符存储在字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53695657/

相关文章:

php - print_r 输出为字符串,仅返回最后一项

c# - 正确分配对列表的引用 c#

c# - 如何在 C# 中使用正则表达式删除 < 和 > 之间的字符?

c - 使用 POSIX 共享内存和信号量以 block 的形式传输文件

c - 全局和局部作用域变量(为什么第二个打印输出是 28?)

将 int 转换为 float 到 hex

javascript - 使用javascript在数组中查找一组对象

java - 如何从使用数组构建的堆栈中删除元素?

说明 Windows 中的虚拟内存管理器如何获取内存映射文件数据

ruby - 试图理解为什么它不能 "convert string to integer"(Ruby 直方图迭代哈希)