如何在字符串中存储元素的第一个字符?例如。如果我跑
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;
}