简体   繁体   English

如何在C中将char转换为字符串?

[英]How to cast char to string in C?

Im new to C and i encounter a problem with using strcat(). 我是C语言新手,使用strcat()时遇到问题。 I looked up strcat and noticed that it takes string as arguments but when i split items from a char array is a char and when i use it as a argument for strcat it prints out error. 我查了一下strcat,发现它以字符串作为参数,但是当我从char数组中拆分项目时,是一个char,当我将其用作strcat的参数时,它会打印出错误。

#include <stdio.h>
#include <string.h>
int main()
{   
char a[10]="abcdefg123";
char *pa=a;
char *out[2]={"",""};
int counter=0;
while(*pa != '\0'){
    if (counter%2==0){
        strcat(out[0],*pa);
    }
    else{
    strcat(out[1],*pa);
    }

    counter++;
    pa++;    
   } 
printf("%s,%s\n",out[0],out[1]);

return 0;
}

the purpose of the code is to split a string into two string that each contain all the characters in odd position or even position.However, when im tring to dereference the char pointer all i get is a Char but it seems i need string 该代码的目的是将一个字符串拆分为两个字符串,每个字符串包含所有位于奇数位置或偶数位置的字符。但是,当我试图取消对char指针的引用时,我得到的只是一个Char,但似乎我需要一个字符串

Use a temporary string in strcat instead of strcat(out[0],*pa); strcat使用临时字符串,而不是strcat(out[0],*pa); .

Also, make sure that you allocate enough memory for out . 另外,请确保为out分配了足够的内存。

int main()
{   
   char a[10]="abcdefg123";
   char temp[2] = {0};
   char *pa=a;

   // This is not good for `strcat`.
   // char *out[2]={"",""};

   // Use this instead.
   char out[2][20]={"",""};

   int counter=0;
   while(*pa != '\0'){
      temp[0] = *pa;
      if (counter%2==0){
         strcat(out[0], temp);
      }
      else{
         strcat(out[1], temp);
      }

      counter++;
      pa++;    
   } 
   printf("%s,%s\n",out[0],out[1]);

   return 0;
}

Point 1. As per the man page of strcat() 点1.按照strcat()手册页

. .. the dest string must have enough space for the result. .. dest字符串必须有足够的空间用于结果。

Point 2. The second argument for strcat() is const char * , so the call cannot be strcat(out[0],*pa); strcat()的第二个参数是const char * ,因此调用不能为strcat(out[0],*pa); . You need to use a temporary array for that, which will hold only the value *pa . 您需要为此使用一个临时数组,该临时数组将仅保留值*pa Otherwise, you can make use of strncat() like 否则,您可以像这样使用strncat()

 strncat(out[0], pa, 1);  // copy only 1 char

In later case, you don't need to have any temporary array. 在以后的情况下,您不需要任何临时数组。

Reference: From man page, again, 参考:再次在手册页中,

The strncat() function is similar, except that it will use at most n bytes from src and src does not need to be null-terminated if it contains n or more bytes. strncat()函数与之类似,不同之处在于它将最多使用src n个字节,并且如果src包含n或更多字节,则不需要以空值结尾。

strcat() requires a pointer to a null-terminated string. strcat()需要一个以null终止的字符串的指针。 You are dereferencing a pointer (with the * operator) which gives a char. 您正在取消引用给出字符的指针(使用*运算符)。 You cannot simply cast a char to a pointer to sting. 您不能简单地将char转换为指向sting的指针。 You might want to be using memcpy() instead of strcat(), but for copying single bytes a simple assignment using * operators on both the left and right sides would be fine. 您可能希望使用memcpy()而不是strcat(),但是对于复制单个字节,可以在左侧和右侧使用*运算符进行简单分配。 But as others have pointed out your code isn't allocating space for you to copy the chars into, so you're going to need to make additional changes to fix that. 但是正如其他人指出的那样,您的代码并没有为复制char分配空间,因此您将需要进行其他更改来解决此问题。 Also, you'll have to remember to copy a final null byte to the end of both your output strings. 另外,您还必须记住将最终的空字节复制到两个输出字符串的末尾。

In C, a "string" is really just a pointer to a character; 在C语言中,“字符串”实际上只是指向字符的指针。 the string runs from that character to the terminating 0 byte (the NUL ). 字符串从该字符开始到终止的0字节( NUL )。

If you dereference a string pointer, you get the character at that position. 如果取消引用字符串指针,则会在该位置获得字符。 If the pointer is pointing to the start of the string, you get the first character of the string. 如果指针指向字符串的开头,则将获得字符串的第一个字符。

Your program has some problems. 您的程序有一些问题。 For one, you need to allocate space for the new strings. 首先,您需要为新字符串分配空间。 strcat() will try to copy characters wherever you tell it to, but it's your job to make sure that there is room there and that it's okay to write there. strcat()会尝试将字符复制到任何地方,但这是您的工作,以确保在那里有空间并且可以在那儿书写。 The declaration of out just declares two pointers, and initializes them to point to a zero-length constant string. out的声明只是声明了两个指针,并将它们初始化为指向长度为零的常量字符串。 Instead, you need to allocate storage, something like: 相反,您需要分配存储空间,例如:

char out0[64], out1[64];
char *out[]={out0, out1};

This makes two output buffers of 64 characters each, then sets up out with pointers to them. 这使得每64个字符两个输出缓冲器,然后建立out与指向它们的指针。

Another problem: you declared a length of 10 for your char array, but then you initialize it with a length-10 string. 另一个问题:您为char数组声明了10的长度,但是随后使用length-10字符串对其进行了初始化。 This means there is no room for a terminating NUL byte and C won't put one. 这意味着没有空间可用于终止NUL字节,C不会放一个。 Then strcpy() or strcat() will copy extra garbage from the string, until there happens to be a NUL byte. 然后strcpy()strcat()将从字符串中复制多余的垃圾,直到碰巧有一个NUL字节为止。 If you are lucky there will be one right away and you won't spot the error, but if you aren't lucky you will get weird garbage. 如果幸运的话,马上就会有一个错误,并且不会发现错误,但是如果不幸运的话,您将得到奇怪的垃圾。

Just let the compiler count how many bytes in your string and do the right thing. 只需让编译器计算您的字符串中有多少字节,然后做正确的事即可。 Leave out the length: 省略长度:

char a[]="abcdefg123";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM