如何使用 strcpy 将字符串复制到字符数组中
How to copy a string into a char array with strcpy
我试图将值复制到字符中。
我的字符数组是
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"
呵呵
相关文章:
- 指向指向字符数组的指针数组的指针
- 比较字符数组
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 使用无符号字符数组有效存储内存
- 错误:字符数组的初始值设定项太多
- 对字符数组中的元素执行逐位操作
- C++ 无法在字符数组中使用 for 循环打印字母模式
- 如何在 C++ 中从文件中读取字符数组(带有一些空格)
- C++ 传递二维字符数组
- 无法在 C++ 中输入字符数组
- 字符数组中的元素数
- 我的目标是编写一个程序来计算和存储字符串在字符数组中出现的位置
- 使用字符数组作为 Map 中的键
- C++:__aligned(__alignof__) 导致字符数组数据出现问题?
- 按顺序声明的字符数组重叠
- 在 C++ 中字符串的大小与字符数组的大小
- 寻找一种更好的方法来表示无符号字符数组
- 如何打印 2D 字符数组C++
- 从字符数组的元素中减去'a'是什么意思
- 我是否不正确地集中了这些字符数组?