C Language: Change the contents of a string array

﹥>﹥吖頭↗ 提交于 2019-12-13 09:54:43

问题


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.



来源:https://stackoverflow.com/questions/21683119/c-language-change-the-contents-of-a-string-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!