1. 程式人生 > >c++中atoi、substr、c_str用法詳解

c++中atoi、substr、c_str用法詳解

最近寫程式中用到這幾個函式,下面將這幾個函式的用法總結如下:

1.atoi函式。

功能:將字串轉換成長整型數。

用法:int atoi(const char *nptr)

示例程式碼如下:

#include <stdio.h>
#include <stdlib.h>

//atoi函式是把字串轉換成長整形數。用法是: int atoi(const char *nptr)
int main()
{
	int n;
	char *str = "12345.67";

	n = atoi(str);
	printf("string = %s integer = %d\n", str, n);
	return 0;

}

此時輸出為:

string = 12345.67  integer = 12345.

2.substr函式。

功能:複製子字串,要求從指定位置開始,並具有指定的長度。如果沒有指定長度或者超出了源字串的長度,

則子字串將延續到源字串的結尾。

用法:basic_string::substr(size_type  _Off=0, size_type  _Count = npos) const;

引數說明:_Off ---所需子字串的起始位置。字串中第一個字元的索引為0,預設值是0.

                 _Count ---複製的字元數目。

返回值:返回一個子字串,從指定位置開始。

程式碼示例:

#include<string>
#include<iostream>
using namespace std;
int main()
{
	string str1("This is a function test");
	cout << "The original string str1 is:" << endl;
	cout << str1 << endl;
	basic_string<char>str2 = str1.substr(5, 13);
	cout << "The substring str1 copied is: " << str2 << endl;
	basic_string<char>str3 = str1.substr();
	cout << "The default substring str3 is:" << endl;
	cout << str3 << endl;
	cout << "which is the entire original string." << endl;
	return 0;
}

輸出為:

3.c_str函式。

功能:它是String類中的一個函式,它返回當前字串的首字元地址。

標準標頭檔案<cstring>包含操作c-串的函式庫。這些庫函式表達了我們希望使用的幾乎每種字串操作。

當呼叫庫函式時,客戶程式提供的是string型別引數,而庫函式內部實現用的是c-串。

因此需要將string物件,轉化為char*物件,c_str就提供了這樣一種方法。它返回const char*的指向字元陣列的指標。

程式碼示例:

#include <iostream>
#include <string> 
using namespace std;
int main()
{
	string add_to = "hello!";
	const string add_on = "c++";
	const char *cfirst = add_to.c_str();
	cout << cfirst << endl;
	const char *csecond = add_on.c_str();
	cout << csecond << endl;
	char *copy = new char[strlen(cfirst) + strlen(csecond) + 1];
	strcpy(copy, cfirst);//複製字串
	cout << copy << endl;
	strcat(copy, csecond);//字串連線
	add_to = copy;
	cout << "copy: " << copy << endl;
	delete[] copy;
	cout << "add_to: " << add_to << endl;
	return 0;
}

輸出: