程序竞赛中常用的C语言字符串处理函数
前言:
最好是使用C++的std::string
,但是有些情况下,比如字符串比较等,反而是C风格的字符串比较灵活。以下列举常用的函数。
字符串操作
char* strcpy( char* dest, const char* src )
把src
的内容复制到dest
中,返回dest
。如果dest
字符长度不够,函数无法处理这种情况,是不安全的。char *strcat( char *dest, const char *src )
把src
追加到dest
后面,返回dest
#include <bits/stdc++.h> using namespace std; int main() { char s[20] = "hello world !"; char s1[20] = "Goodbye"; strcat(s, s1); cout << s << endl; cout << strlen(s) << endl; return 0; }
strlen(const char* s)
测试s的长度。长度是实际有效的。#include <bits/stdc++.h> using namespace std; int main() { char s[20] = "hello world !"; cout << strlen(s) << endl; return 0; } // 输出 13
strcmp(const char* s1, const char* s2)
比较s1
和s2
的字典序,如果s1<s2
返回负数,s1==s2
返回0,s1>s2
返回正数。
字符串转换操作
double strtod (const char* str, char** endptr)
转换字符串中的浮点数据,并返回。#include <bits/stdc++.h> using namespace std; int main() { char s[30] = "123.123 456.456"; char* pEnd; double d = strtod(s, &pEnd); cout << d << endl; cout << s << endl; d = strtod(pEnd, nullptr); cout << d << endl; cout << s << endl; return 0; } /* 123.123 123.123 456.456 456.456 123.123 456.456 */
注意,转换的时候,不要有其他的杂项字符,否则会转化成0;
double atof (const char* str)
把str
转换成浮点型返回#include <bits/stdc++.h> using namespace std; int main() { char s[]="3.14"; cout<<atof(s)<<endl; return 0; }
不要有杂项字符!
int atoi(const char* str)
把str
转化成整型
字符检查:
isalpha()
检查是否为字母字符isupper()
检查是否为大写字母字符islower()
检查是否为小写字母字符isdigit()
检查是否为数字isxdigit()
检查是否为十六进