简体   繁体   English

如何在没有字符串函数的情况下将新字符串分配给char数组

[英]How to assign a new string to char array without string functions

I am looking to modify a char array with different strings, like a temp char array which takes various strings. 我正在寻找用不同的字符串修改char数组,例如使用各种字符串的temp char数组。 Let's say a char array A[10] = "alice", how to assign A[10] = "12". 假设一个char数组A [10] =“ alice”,如何分配A [10] =“ 12”。 Without using string functions? 不使用字符串函数?

TIA TIA

In C, a string is just an array of type char that contains printable characters followed by a terminating null character ( '\\0' ). 在C中,字符串只是char类型的数组,其中包含可打印字符,后跟一个终止的空字符( '\\0' )。

With this knowledge, you can eschew the standard functions strcpy and strcat and assign a string manually: 有了这些知识,您就可以避开标准函数strcpystrcat并手动分配字符串:

A[0] = '1';
A[1] = '2';
A[2] = '\0';

If there were characters in the string A beyond index 2 , they don't matter since string processing functions will stop reading the string once they encounter the null terminator at A[2] . 如果字符串A中的字符超出索引2 ,则它们无关紧要,因为一旦字符串处理函数在A[2]处遇到空终止符,它们就会停止读取字符串。

it's like Govind Parmar's answer but with for loop. 就像Govind Parmar的答案,但是带有for循环。

#include <stdio.h>
#include <stdlib.h>
int main()
{
    char str[11] = "hello world";
    char new[5] = "2018";   
    int i = 0;

    for (i; new[i] != '\0'; i++)
         str[i] = new[i];

    str[i] = '\0';

    printf("str => '%s' ",str);

    return 0;
}

output : 输出:

str => '2018'                                                                                                              

Well since string array is noting but pointer to array you can simply assign like this 好吧,因为字符串数组是值得注意的,但指向数组的指针可以像这样简单地分配

int main(void) {
    char *name[] = { "Illegal month",
                            "January", "February", "March", "April", "May", "June",
                            "July", "August", "September", "October", "November", "December"
    };
    name[10] = "newstring";
    printf("%s",name[10]);
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM