C/C++ 常用函数(持续更新)

1. strchr()函数 和 strrchr() 函数

strchr
定义于头文件 <string.h>
const char *strchr( const char *str, int ch );
寻找ch(按照如同(char)ch的方式转换成char后)在str所指向的空终止字节字符串(每个字符都被看做unsigned char)中的首次出现位置。终止的空字符被认为是字符串的一部分,并且能在寻找'\0'时被找到。
若str不是指向空终止字节字符串的指针,则行为未定义。

参数
str - 指向待分析的空终止字节字符串的指针
ch - 要查找的字符

返回值
指向str找到的字符的指针,在未找到该字符时返回空指针。

示例

/* strchr example */
#include <stdio.h>
#include <string.h>
 
int main ()
{
  char str[] = "This is a sample string";
  char * pch;
  printf ("Looking for the 's' character in \"%s\"...\n",str);
  pch=strchr(str,'s');
  while (pch!=NULL)
  {
    printf ("found at %d\n",pch-str+1);
    pch=strchr(pch+1,'s');
  }
  return 0;
}
/*Looking for the 's' character in "This is a sample string"...
found at 4
found at 7
found at 11
found at 18*/

strrchr 
定义于头文件 <string.h>
const char *strrchr( const char *str, int ch );
char *strrchr( char *str, int ch );
找到最后一次出现的字符ch中的字节串所指向的str.

参数
str - 指向待分析的空终止字节字符串的指针
ch - 要查找的字符

返回值
str,或NULL找到的字符的指针,如果没有这样的字符被找到

示例

/* strrchr example */
#include <stdio.h>
#include <string.h>
 
int main ()
{
  char str[] = "This is a sample string";
  char * pch;
  pch=strrchr(str,'s');
  printf ("Last occurence of 's' found at %d \n",pch-str+1);
  return 0;
}
/*Last occurence of 's' found at 18 */
在上面两个函数中返回值为const char*或char*与搜索的字符串指针类型为const char*或char*可以是任意一种组合。

c_ctr
定义于头文件 <string.h>
const char *c_str();
c_str()函数返回一个指向正规C字符串的常量指针, 内容与本string串相同.(其实它指向的是string对象内部真正的char缓冲区),所以返回const,以防止用户的修改。

这是为了与c语言兼容,在c语言中没有string类型,必须通过string对象的成员函数c_str()把string 对象转换成c中的字符串样式。

参数

返回值
const char* 指向常量的指针

示例

const char* c;  
std::string s = "1234";  
c = s.c_str();  
std::cout << c << std::endl; //输出:1234  
s = "abcd";  
std::cout << c << std::endl; //输出:abcd  
fread
clock()

猜你喜欢

转载自blog.csdn.net/qq_29621351/article/details/79819506