C++——C字符串

C字符串

C字符串是一个字符数组,以'\0'(空终结符)结尾。可以使用C++库中的C字符串函数操作C字符串。

//初始化C字符串
char city[] = "Beijing";
//求数组长度
cout << sizeof(city)/sizeof(city[0]);
//结果为:8

结果解释:Beijing是7个字符,外加一个空终结符'\0'

C字符串和一般的字符数组的区别就在于:C字符串的最后一个字符一定是'\0',而一般的字符数组可以以任何字符结尾。看下面的例子

//是一个C字符串,有8个字符
char city1[] = "Beijing";

//不是C字符串,是一个普通的字符数组,有7个字符
char city2[] = {'B', 'e', 'i', 'j', 'i', 'n', 'g'}

在键盘输入C字符串和输出C字符串

#include <iostream>

using namespace std;

int main()
{
    char city[100];
    cout << "请输入城市:";
    cin >> city;
    cout << "你输入的城市是:" << city << endl;
    return 0;
}

运行结果:

 如果输入的城市里面有空格(New York),可以使用cin.getline()函数

#include <iostream>

using namespace std;

int main()
{
    char city[100];
    cout << "请输入城市:";
    cin.getline(city,100);
    cout << "你输入的城市是:" << city << endl;
    return 0;
}

运行结果:

 C字符串函数

注:1) 下面的函数都定义在<cstring>头文件下(除转换函数atoi, atof, atol定义在<cstdlib>头文件下)

  2)size_t是一个C++类型,一般与unsigned int相同

函数 描述
size_t strlen(char s[]) 返回字符串长度,即在空终结符之前的个数
strcpy(char s1[], const char s2[]) 把字符串s2复制到s1中
strncpy(char s1[], const char s2[], size_t n) 把字符串s2的前n个字符复制到s1中
strcat(char s1[], const char s2[]) 把字符串s2拼接到s1中
strncat(char s1[], const char s2[], size_t n) 把字符串s2的前n个字符拼接到s1中
int strcmp(char s1[], const char s2[]) 判断s1小于、等于或大于s2,分别返回小于0、等于0、大于0的数
int strncmp(char s1[], const char s2[], size_t n) 只比较s1与s2的前n个字符
int atoi(char s[]) 返回字符串对应的int型值
double atof(char s[]) 返回字符串对应的double型值
long atol(char s[]) 返回字符串对应的long型值
void itoa(int value, char s[], int radix) 基于一个指定的集数,获得字符串的整数值(可用于进制转换)

主要说明一下后面的几个转换函数:

atoi

#include <iostream>
#include <cstdlib>

using namespace std;

int main()
{
    char s1[] = "11";
    char s2[] = "23";
    cout << s1 << " + " << s2 << " = " << atoi(s1)+atoi(s2) << endl;
    return 0;
}

atof, atol同理

itoa

#include <iostream>
#include <cstdlib>

using namespace std;

int main()
{
    char s1[10];
    char s2[10];
    itoa(100, s1, 16);
    itoa(10, s2, 2);

    cout << "100的16进制是:" << s1 << endl;
    cout << "10的2进制是:" << s2 << endl;
    return 0;
}

运行结果:

猜你喜欢

转载自www.cnblogs.com/bwjblogs/p/12655693.html
今日推荐