Zarak1
Zarak1

Reputation: 113

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. Let's say a char array A[10] = "alice", how to assign A[10] = "12". Without using string functions?

TIA

Upvotes: 0

Views: 769

Answers (3)

Holy semicolon
Holy semicolon

Reputation: 1359

it's like Govind Parmar's answer but with for loop.

#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'                                                                                                              

Upvotes: 2

koneru nikhil
koneru nikhil

Reputation: 339

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;
}

Upvotes: 0

Govind Parmar
Govind Parmar

Reputation: 21532

In C, a string is just an array of type char that contains printable characters followed by a terminating null character ('\0').

With this knowledge, you can eschew the standard functions strcpy and strcat and assign a string manually:

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].

Upvotes: 2

Related Questions