C Language: Change the contents of a string array

2019-09-22 02:20发布

问题:

I'm having trouble changing the contents of a variable holding a string. I'm probably thinking of this too literally compared to an int and not as an array. Maybe have to flush array first? Much thanks.

// declare with maximum size expected +1 (for terminator 0)
char myString1[20] = "Hello"; //declare and assign one line - OK
myString1[20] = "Hello Longer"; // change contents - fails
myString1[] = "Hello Longer"; // change contents - fails
myString1 = "Hello Longer"; // change contents - fails

回答1:

This is C, not an object oriented language that takes care of copying strings for you. You'll need to use the string library. For example:

char myString1[20] = "Hello";
strncpy(myString1, "Hello Longer", 20);


回答2:

You need to use a function like strncpy to copy a string.



回答3:

In C the assigment operator = does not work for arrays. With the only exception of initialisers.


More over this

myString1[20] = "Hello Longer"

is a type mismatch as myString1[20] is a char to which you obviously only can assign a char or something that can be converted to a char.


To trick this you could do:

#include <stdio.h>

struct Str_s
{
  char myString[20];
};

int main(void)
{  
  struct Str_s str1 = {
    "Hello"
  };

  struct Str_s str2 = {
    "World"
  };

  printf("str1='%s'\nstr2='%s'\n", str1.myString, str2.myString);

  str2 = str1;

  printf("str1='%s'\nstr2='%s'\n", str1.myString, str2.myString);

  return 0;
}

This should print:

Hello World
Hello Hello

Obviously the assignment operator works for structs.