细谈字符串:字符数组,string

C++中处理字符串的两种方法:
1.字符数组,如:
    char str[10];
    初始化的方法:
    char str[10] = {'h','e','l','l','o'};// char str[10] = "hello"; 这样是错误的做法
    或者
    char str[10];
    for(int i = 0; i < 10; i++)
    {   char t;
        cin >> t;
        str[i] = t;
    }
但是输出str可以直接:
cout << str << endl;
 
2.字符串
string str = "hello";
cin >>str;
cout << str;
 
3.字符串长度获取
数组字符串可以通过循环获取:
int i = 0;
for(i; str[i] != '\0'; i++);

注意:sizeof是C/C++中的一个操作符(operator),简单的说其作用就是返回一个对象或者类型所占的内存字节数。
char[50] c; 则sizeof(c) = 50
因为sizeof(char) = 1;
此外sizeof(int)is 4;
if int a[10],then sizeof(a) is 40;
sizeof(string) = 8;
string长度获取:
s.size();
s.length();
注意:strlen获取长度只能是数组类型字符串,并且声明为
      #include <string.h>或者 #include <cstring>
比如:
 #include <iostream>
 #include <string.h>
using namespace std;
int main()
{
 char* s = "hello";// 或者 char s[10] = {'h','e','l','l','o'};
 cout << strlen(s) << endl;
 return 0;
}
4.#include <string>
  #include <cstring>
  #include <string.h>
(1)#include <string>
    一些常用的函数:
    s.size()
    s.length()
    s.resize(n) 保留字符串前n位
    s.capacity() 返回当前vector在重新进行内存分配以前所能容纳的元素数量。
    s.reserve()函数reserve()将字符串的容量设置为至少size. 如果size指定的数值要小于当前字符串中的字符数(亦即  size<this→size()), 容量将被设置为可以恰好容纳字符的数值. reserve()以线性时间(linear time)运行。它最大的用 处是为了避免反复重新分配缓冲区内存而导致效率降低,或者在使用某些STL操作(例如std::copy)之前保证缓冲区够大。
    s.empty() =0为空
    getline(cin, string)//Get line from stream into string
(2)#include <cstring>
Copying:
memcpy
Copy block of memory (function )
memmove
Move block of memory (function )
strcpy
Copy string (function )
strncpy
Copy characters from string (function )
Concatenation:
strcat
Concatenate strings (function )
strncat
Append characters from string (function )
Comparison:
memcmp
Compare two blocks of memory (function )
strcmp
Compare two strings (function )
strcoll
Compare two strings using locale (function )
strncmp
Compare characters of two strings (function )
strxfrm
Transform string using locale (function )
Searching:
memchr
Locate character in block of memory (function )
strchr
Locate first occurrence of character in string (function )
strcspn
Get span until character in string (function )
strpbrk
Locate characters in string (function )
strrchr
Locate last occurrence of character in string (function )
strspn
Get span of character set in string (function )
strstr
Locate substring (function )
strtok
Split string into tokens (function )
Other:
memset
Fill block of memory (function )
strerror
Get pointer to error message string (function )
strlen
Get string length (function )
Macros
NULL
Null pointer (macro )
Types
size_t
Unsigned integral type (type )

猜你喜欢

转载自blog.csdn.net/newandbetter/article/details/80273141
今日推荐