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

输出:




  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值