[这是我必须构建的函数,该函数返回一个包含您的出生日期,您的姓名和您母亲的姓名的字符串”秘密身份”(例如,如果“ 02/12/2007”,“ LUCY TOLKIEN”,和“ JENNIFER”返回“ 20070212LT * J”),但我正在努力将字符(例如“ LUCY TOLKIEN”的“ L”和“ T”)连接到称为“秘密身份”的字符串。我希望我能解释清楚。到目前为止,我所做的是:
int length(char * s) {
int i, n = 0;
for (i = 0; *(s + i) != '\0'; i++) {
n++;
}
return n;
}
void concatenate(char * s, char * t) {
int i = 0;
int j;
while (*(s+i) != '\0') {
i++;
}
for (j = 0; *(t+i) != '\0'; j++) {
*(s + i) = *(t + j);
i++;
}
*(s + i + 1) = '\0';
}
void copy(char * dest, char * orig) {
int i;
for (i = 0; *(orig + i) != '\0'; i++) {
*(dest + i) = *(orig + i);
}
*(dest + i) = '\0';
}
void geraIdentidade(void) {
char * ident;
int lname, ldate, lmom;
char name[80];
printf("Name: ");
scanf(" %[^\n]s", name);
lname = length(name);
char date[11];
printf("Date: ");
scanf(" %[^\n]s", date);
ldate = length(date);
char mom[20];
printf("Name (mom): ");
scanf(" %[^\n]s", mom);
lmom = length(mom);
char day[3], month[3], year[5];
int i, j, k;
for (i = 0; date[i] != '/'; i++) {
day[i] = date[i];
day[i + 1] = '\0';
}
for (j = 3, i = 0; date[j] != '/'; j++, i++) {
month[i] = date[j];
month[i + 1] = '\0';
}
for (k = 6, i = 0; k <= 9; k++, i++) {
year[i] = date[k];
year[i + 1] = '\0';
}
ident = (char*)malloc((lmom + ldate + lname) * sizeof(char)); //change lenght
if (ident != NULL) {
copy(ident, year);
concatenate(ident, month);
concatenate(ident, day);
}
else {
return NULL;
}
printf("%s\n", ident);
}
int main(void) {
geraIdentidade();
return 0;
}
我认为,您的代码中有3个功能:
int length(char * s)
void concatenate(char * s, char * t)
void copy(char * dest, char * orig)
[在<string.h>
中使用某些C标准函数时,可以使代码更容易编写:
size_t strlen(const char *s); // for length
char *strcpy(char *dest, const char *src); // for copy
char *strcat(char *dest, const char *src); // for concatenation
[当您要串联string
和character
时,只需将character
字符添加到要串联的字符上,即可将string
转换为\0
。例如,如果要将T
连接到字符串20070212L
:
#include <stdio.h>
#include <string.h>
int main()
{
char str[11] = "20070212L";
char ch[2] = "\0";
ch[0] = 'T';
strcat(str, ch);
printf("str = %s", str);
return 0;
}
输出:
str = 20070212LT