学了这么长时间c++,一直没怎么搞清楚获取字符串长度的函数到底该怎么用,今天实在受不了这种你那个模糊的感觉,所以趁热打铁来总结。

主要对sizeof(), strlen(), str.length(), str.size()函数做总结:

1. sizeof()

获取所占空间的字节数

#include <iostream>
using namespace std;

int main()
{
  char a[] = {'a','b','c'};
  int len = sizeof(a);
  cout<<len;
  return 0;
}

输出:3

#include <iostream>
using namespace std;

int main()
{
  int a[] = {1,2,3};
  int len = sizeof(a);
  cout<<len;
  return 0;
}

输出:12

 

2. strlen(char *s)

s是指定字符串,返回该字符串的长度,不包括结束符'/0',需包含#include<string.h>

#include <iostream>
#include <string.h>
using namespace std;

int main()
{
  char *a = "abc";
  char b[10] = "defg";

  int len1 = strlen(a);
  int len2 = strlen(b);
  int len3 = sizeof(b);

  cout<<"len1="<<len1<<endl;
  cout<<"len2="<<len2<<endl;
  cout<<"len3="<<len3<<endl;
  return 0;
}

注:char b[10] = "defg"声明了一个大小为10的字符数组,但只有前4个被初始化了,其余全为0,所以sizeof(b)为10;

  如果声明char[6] = "abcdef"会报错,因为数组大小为6,应当留出最后一个位置用来存'/0'.

 

3.str.length()和str.size()

两个函数的用法和效果是一样的,都用来求string字符串的长度

#include <iostream>
#include <string>
using namespace std;

int main()
{
  string s = "asd";
  int len1 = s.size();
  int len2 = s.length();
  cout<<len1<<endl;
  cout<<len2<<endl;
  return 0;
}

输出:3

   3

总结:求空间大小 ---sizeof()

   求char字符串长度---strlen(char *)

   求string字符串长度---s.size()和s.length()

 

posted on 2017-07-27 21:22  小小糖果tt  阅读(2035)  评论(0)    收藏  举报