[英]How can I concatenate characters to a string in C?
這是一個練習,我必須構建一個 function,它返回一個名為“秘密身份”的字符串,其中包含您的出生日期、您的姓名和您母親的姓名(例如,如果“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
時,你只需要通過將\0
字符添加到要連接的字符來將character
轉換為string
。 例如,如果要將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;
}
output:
str = 20070212LT
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.