如何使用 strcpy 将字符串复制到字符数组中

How to copy a string into a char array with strcpy

本文关键字:字符 数组 复制 字符串 何使用 strcpy      更新时间:2023-10-16

我试图将值复制到字符中。

我的字符数组是

char sms_phone_number[15];

顺便说一句,可以告诉我我是否应该写(有什么好处/区别?

char * sms_phone_number[15]

下面显示一个字符串:"+417611142356">

splitedString[1]

我想把这个价值赋予sms_from_number

// strcpy(sms_from_number,splitedString[1]);   // OP's statement 
strcpy(sms_phone_number,splitedString[1]);  // edit 

我有一个错误,我想是因为splitedString[1]是一个字符串,不是吗?

sim908_cooking:835:错误:从"字符"到"字符*"的转换无效

那么我怎样才能正确复制它。我也尝试过使用sprintf,但没有成功。

非常感谢您的帮助。干杯

我像这样声明spliedString

// SlitString
#define NBVALS 9
char *splitedString[NBVALS];

我有那个功能splitString("toto,+345,titi",slitedString(

void splitString(char *ligne, char **splitedString)
{
  char *p = ligne;
  int i = 0;
  splitedString[i++] = p;
  while (*p) {

    if (*p==',') {
      *p++ = '';
      if (i<NBVALS){
         splitedString[i++] = p;
      }
    } 
    else
    {
      p++;
    }
  }
  while(i<NBVALS){
    splitedString[i++] = p; 
  }
}

如果我对拆分字符串显示执行 for,它会显示这个

for(int i=0;i<4;i++){
Serialprint(i);Serial.print(":");Serial.println(splitedString[i]);
}
//0:toto
//1:+4176112233
//2:14/09/19

我也声明并想复制..

char sms_who[15];
char sms_phone_number[15];
char sms_data[15];
//and I want to copy 
strcpy(sms_who,splitedString[0]
strcpy(sms_phone_number,splitedString[1]
strcpy(sms_date,splitedString[2]

我知道,我对字符和指针 * :o(

声明:

  char * SplittedString[15];

声明指向字符的指针数组,也称为 C 样式字符串。

鉴于:

  const char phone1[] = "(555) 853-1212";
  const char phone2[] = "(818) 161-0000";
  const char phone3[] = "+01242648883";

您可以将它们分配给SplittedString数组:

  SplittedString[0] = phone1;
  SplittedString[1] = phone2;
  SplittedString[2] = phone3;

为了帮助您更多,上述作业应该是:

  SplittedString[0] = &phone1[0];
  SplittedString[1] = &phone2[0];
  SplittedString[2] = &phone3[0];

根据定义SplittedStrings数组包含指向单个字符的指针,因此最后一组赋值是正确的版本。

如果允许,首选std::string而不是char *std::vector数组。

你需要的是一个字符串向量:

std::vector<std::string> SplittedStrings(15);

编辑 1:

提醒:为您的spliedString分配空间。

您的spliedString应该是预分配的数组:

  char spliedString[256];  

或动态分配的字符串:

  char *spliedString = new char [256];

字符串和字符可能会让菜鸟感到困惑,特别是如果您使用过其他更灵活的语言。

char msg[40];  // creates an array 40 long that can contains characters
msg = 'a';     // this gives an error as 'a' is not 40 characters long 
(void) strcpy(msg, "a");              // but is fine : "a"
(void) strcat(msg, "b");              // and this    : "ab"
(void) sprintf(msg,"%s%c",msg, 'c');  // and this    : "abc"