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;
}

輸出:




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章