在 C++ 中將字串轉換為字元陣列


這是一個 C++ 程式,用於在 C++ 中將字串轉換為字元陣列。這可以透過多種方式完成

型別 1

演算法

Begin
   Assign value to string m.
   For i = 0 to sizeof(m)
      Print the char array.
End

示例程式碼

 線上示例

#include<iostream>
#include<string.h>
using namespace std;
int main() {
   char m[] = "Tutorialspoint";
   string str;
   int i;
   for(i=0;i<sizeof(m);i++) {
      str[i] = m[i];
      cout<<str[i];
   }
   return 0;
}

型別 2

我們可以簡單地呼叫 strcpy() 函式將字串複製到字元陣列中。

演算法

Begin
   Assign value to string s.
   Copying the contents of the string to char array using strcpy().
End

示例程式碼

 線上示例

#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main() {
   string str = "Tutorialspoint";
   char c[str.size() + 1];
   strcpy(c, str.c_str());
   cout << c << '\n';
   return 0;
}

輸出

Tutorialspoint

型別 3

我們可以避免使用在 c 中基本使用的 strcpy(),具體方法是

std::string::copy instead.

演算法

Begin
   Assign value to string s.
   copying the contents of the string to char array using copy().
End

示例程式碼

 線上示例

#include <iostream>
#include <string>
using namespace std;
int main() {
   string str = "Tutorialspoint";
   char c[str.size() + 1];
   str.copy(c, str.size() + 1);
   c[str.size()] = '\0';
   cout << c << '\n';
   return 0;
}

輸出

Tutorialspoint

更新於:2019 年 7 月 30 日

3K+ 次檢視

開始您的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.