1. 程式人生 > >函式和C-風格字串

函式和C-風格字串

將字串作為函式的引數

#incude <iostream>
unsigned short c_in_str(char *,char);
int main()
{
	unsigned short chs;
	char name[] = "zhangqian";
	chs = c_in_str(name,'n')
	std::cout << chs << std::endl;
}

unsigned short c_in_str(char *pstr,char ch)
{
	unsigned short i = 0;
	while(*pstr)
	{
		if(*pstr == ch)
		{
			i++;
		}
		pstr++;
	}
}

返回字串 函式無法返回字串,但可以返回字串的地址

//返回char指標的函式

#include <iostream>
using namespace std;
char * chback(char,int);

int main()
{
	char * z = chback('z',10);
	cout << z << endl;
	delete []z;
	
	return 0;
}

char * chback(char ch,int n) //顯示相同字元ch,重複次數n,
{
	char * pstr;
	pstr = new char[n+1];
	pstr[n] = '\0';
	while(n-- > 0)
	{
		pstr[n] = ch; 
	}
	return pstr;
}