Char数组的赋值

时间:2024-11-12 14:08:40
1、定义的时候直接用字符串赋值
char a[10]="hello";   //sizeof(a)10
char a[]="hello";  //sizeof(a)6
注意:不能先定义再给它赋值,如char a[10]; a[10]="hello";这样是错误的!
2、对数组中字符逐个赋值
char a[10]={'h','e','l','l','o'}; //sizeof(a)10
char a[]={'h','e','l','l','o'}; //sizeof(a)5
3
、利用strcpy
char a[10];

strcpy(a, "hello");

例题:将小写转化为大写
char * CTrunDlg::TrunTo(char ch[])//将小写字母转化为大写
{
       int i=0;
       while (ch!='/0')
       {
              if (ch>='a'&&ch<='z')
              {
                     ch=ch-('a'-'A');
              }
              i++;
       }
       return ch;
}

void CTrunDlg::OnButton1()
{
       char temp[]= "abcDEFg呵呵";
       CString str = "";
//     char ch[10];
//     int i = 0;
       char *pch = TrunTo(temp);
//     for (;*pch!='/0';pch++,i++)
       for (;*pch!='/0';pch++)
       {
//            ch = *pch;
              str+=*pch;
       }
       MessageBox(str);
}