2013年5月8日 星期三

(C++) C-style 字串

C語言中字串是由字元所組成的陣列,字串的名子本身是一個pointer,字串以'\0'字元結尾,有兩種可行的宣告方式:


方式一:
char str[] = {'H', 'e', 'l', 'l', 'o', '\0'};


方式二:
char str[] = "Hello"; (程式會自動加上空字元 '\0')



範例:

#include < iostream >

int main( )
{
    char str[] = "Hello";

    for(int i = 0; i < (sizeof(str)/sizeof(str[0])); ++i)
   {
     if(str[i] == '\0') 
        cout << " null";
    else
       cout << " " << str[i];
   }
  return 0;
}

沒有留言:

張貼留言