1. 程式人生 > >【C++】返回C-風格字串的函式

【C++】返回C-風格字串的函式

假設你要編寫一個返回字串的函式。但是函式無法返回一個字串,但是可以返回字串的地址!這樣效率更高!

函式接受兩個引數:一個字元+一個數組

使用new建立一個長度與陣列引數相等的字串,然後將每個元素都初始化 為該字元,返回新字串的指標

//返回C-風格字串的函式
#include <iostream>
char * buildstr(char c, int n);
int main()
{
	using namespace std;
	int times;
	char ch;

	cout << "輸入一個字元: ";
	cin >> ch;
	cout << "輸入一個整數: ";
	cin >> times;
	char *ps = buildstr(ch, times);
	cout << ps << endl;
	delete [] ps;  //釋放記憶體
	ps = buildstr('+', 20);
	cout << ps << "-Done-" << ps << endl;
	delete [] ps;

	cin.get();
	system("pause");
	return 0;

}

char * buildstr(char c, int n)
{
	char * pstr = new char[n + 1];
	pstr[n] = '\0';
	while (n-->0)
	{
		pstr[n] = c;
	}
	return pstr;
}