在 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
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP