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

180it 2020-10-09 AM 1557℃ 0条

最近写程序中用到这几个函数,下面将这几个函数的用法总结如下:

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

输出为:
2018032621495262.jpg

3.c_str函数。

功能:它是String类中的一个函数,它返回当前字符串的首字符地址。

标准头文件包含操作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;
}

输出:
20180326220335462.jpg

https://blog.csdn.net/KFLING/article/details/79704754

支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

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