웹 프론트엔드 JS 튜토리얼 C_javascript 스킬의 문자열 클래스 사용 요약

C_javascript 스킬의 문자열 클래스 사용 요약

May 16, 2016 pm 03:46 PM
c++ 문자열 클래스

MFC 프로그래밍을 사용해 본 친구들은 CString 클래스에 깊은 인상을 받았을 것 같아요. 실제로 MFC의 CString 클래스는 정말 편리하고 사용하기 쉽습니다. 그런데 MFC 프레임워크를 벗어나면 사용하기 매우 편리한 클래스가 있을까요? 대답은 '예'입니다. 어떤 사람들은 MFC 프레임워크를 사용하지 않더라도 MFC에서 API를 사용하는 방법을 찾을 수 있다고 말할 수 있습니다. 구체적인 작업 방법은 이 문서의 끝부분에 나와 있습니다. 실제로 많은 사람들이 표준 C에서 문자열 클래스 사용을 무시할 수 있습니다. 표준 C에서 제공하는 문자열 클래스 함수도 매우 강력하여 프로젝트 개발 시 일반적으로 사용할 수 있습니다. 이제 출발점으로 삼아 다음과 같이 몇 가지 구체적인 사용법을 나열하겠습니다. 좋습니다. 헛소리는 그만두고 본론으로 들어가겠습니다.

표준 C에서 문자열 클래스를 사용하려면

을 포함해야 합니다.

#include // 가 아니라 이라는 점에 유의하세요. .h가 있는 파일은 C 언어의 헤더 파일입니다.

std::string; 사용

std::wstring 사용;

또는

네임스페이스 std 사용

이제 각각 char 및 wchar_t에 해당하는 string/wstring을 사용할 수 있습니다.

string과 wstring의 사용법은 동일하며 아래 소개에는 string만 사용됩니다.

문자열 클래스 생성자:

string(const char *s); //用c字符串s初始化
string(int n,char c);//用n个字符c初始化

로그인 후 복사

또한 문자열 클래스는 string s1과 같은 기본 생성자와 복사 생성자를 지원합니다. string s2="hello"; 생성된 문자열이 표현하기에 너무 길면 length_error 예외가 발생합니다.

문자열 클래스의 문자 연산:

const char &operator[](int n)const;
const char &at(int n)const;
char &operator[](int n);
char &at(int n);
//operator[]和at()均返回当前字符串中第n个字符的位置,但at函数提供范围检查,当越界时会抛出out_of_range异常,下标运算符[]不提供检查访问。
const 
char *data()const;//返回一个非null终止的c字符数组
const char* c_str()const;//返回一个以null终止的c字符串
int copy(char *s, int n, int pos = 0)const;//把当前串中以pos开始的n个字符拷贝到以s为起始位置的字符数组中,返回实际拷贝的数目

로그인 후 복사

문자열의 특성 설명:

int capacity()const; //返回当前容量(即string中不必增加内存即可存放的元素个数)
int max_size()const; //返回string对象中可存放的最大字符串的长度
int size()const;  //返回当前字符串的大小
int length()const;  //返回当前字符串的长度
bool empty()const;  //当前字符串是否为空
void resize(int len,char c);//把字符串当前大小置为len,并用字符c填充不足的部分

string类的输入输出操作:
string类重载运算符operator>>用于输入,同样重载运算符operator<<用于输出操作。
函数getline(istream &in,string &s);用于从输入流in中读取字符串到s中,以换行符'\n'分开。
로그인 후 복사

문자열 할당:

코드 복사 코드는 다음과 같습니다.
string &operator=(const string &s);//Convert string s 현재 문자열에 할당
string &sign(const char *s);//c 유형 문자열 s로 값 할당
string &sign(const char *s,int n);//c 문자열 s에서 시작하여 n 문자 할당
string &sign(const string &s);//현재 문자열에 문자열 s 할당
string &sign(int n,char c);//현재 문자열에 n 문자 c 할당
string &sign(const string &s,int start,int n);//문자열 s의 시작부터 시작하여 n자를 현재 문자열에 할당
string &sign(const_iterator first, const_itertor last);//첫 번째 반복자와 마지막 반복자 사이의 부분을 문자열

에 할당합니다.

문자열 연결:

코드 복사 코드는 다음과 같습니다.
string &operator =(const string &s);//put string s 현재 문자열의 끝에 연결
string &append(const char *s); //c 유형 문자열 s를 현재 문자열의 끝에 연결
string &append(const char *s,int n);//c 유형 string s의 처음 n자를 현재 문자열의 끝에 연결
string &append(const string &s); //연산자 =()
와 동일 string &append(const string &s,int pos,int n);//문자열 s의 pos부터 시작하여 n자를 현재 문자열의 끝까지 연결
string &append(int n,char c); //현재 문자열의 끝에 n 문자 c
를 추가합니다. string &append(const_iterator first, const_iterator last);//iterator first와 last 사이의 부분을 현재 문자열의 끝까지 연결

문자열 비교:

코드 복사 코드는 다음과 같습니다.
bool 연산자==(const string &s1,const string &s2 )const; //두 문자열을 비교하여 동일한지 확인
">", "<", ">=", "<=", "!=" 연산자는 모두 문자열 비교를 위해 오버로드됩니다.
int Compare(const string &s) const;//현재 문자열과 s의 크기를 비교합니다
int Compare(int pos, int n, const string &s)const;//pos부터 시작하는 n자로 구성된 현재 문자열과 s의 크기를 비교합니다
int Compare(int pos, int n, const string &s, int pos2, int n2) const;//pos에서 시작하는 n자로 구성된 현재 문자열을 s의

과 비교합니다.

int 비교(const char *s) const;
int 비교(int pos, int n,const char *s) const;
int 비교(int pos, int n,const char *s, int pos2) const;
비교 함수는 >인 경우 1, <인 경우 -1, ==
인 경우 0을 반환합니다.

string的子串:

复制代码 代码如下:
string substr(int pos = 0,int n = npos) const;//返回pos开始的n个字符组成的字符串

string的交换:

复制代码 代码如下:
void swap(string &s2); //交换当前字符串与s2的值

string类的查找函数:

int find(char c, int pos = 0) const;//从pos开始查找字符c在当前字符串的位置
int find(const char *s, int pos = 0) const;//从pos开始查找字符串s在当前串中的位置
int find(const char *s, int pos, int n) const;//从pos开始查找字符串s中前n个字符在当前串中的位置
int find(const string &s, int pos = 0) const;//从pos开始查找字符串s在当前串中的位置
//查找成功时返回所在位置,失败返回string::npos的值 
int rfind(char c, int pos = npos) const;//从pos开始从后向前查找字符c在当前串中的位置
int rfind(const char *s, int pos = npos) const;
int rfind(const char *s, int pos, int n = npos) const;
int rfind(const string &s,int pos = npos) const;
//从pos开始从后向前查找字符串s中前n个字符组成的字符串在当前串中的位置,成功返回所在位置,失败时返回string::npos的值 
int find_first_of(char c, int pos = 0) const;//从pos开始查找字符c第一次出现的位置
int find_first_of(const char *s, int pos = 0) const;
int find_first_of(const char *s, int pos, int n) const;
int find_first_of(const string &s,int pos = 0) const;
//从pos开始查找当前串中第一个在s的前n个字符组成的数组里的字符的位置。查找失败返回string::npos 
int find_first_not_of(char c, int pos = 0) const;
int find_first_not_of(const char *s, int pos = 0) const;
int find_first_not_of(const char *s, int pos,int n) const;
int find_first_not_of(const string &s,int pos = 0) const;
//从当前串中查找第一个不在串s中的字符出现的位置,失败返回string::npos 
int find_last_of(char c, int pos = npos) const;
int find_last_of(const char *s, int pos = npos) const;
int find_last_of(const char *s, int pos, int n = npos) const;
int find_last_of(const string &s,int pos = npos) const; 
int find_last_not_of(char c, int pos = npos) const;
int find_last_not_of(const char *s, int pos = npos) const;
int find_last_not_of(const char *s, int pos, int n) const;
int find_last_not_of(const string &s,int pos = npos) const;
//find_last_of和find_last_not_of与find_first_of和find_first_not_of相似,只不过是从后向前查找

로그인 후 복사

string类的替换函数:

string &replace(int p0, int n0,const char *s);//删除从p0开始的n0个字符,然后在p0处插入串s
string &replace(int p0, int n0,const char *s, int n);//删除p0开始的n0个字符,然后在p0处插入字符串s的前n个字符
string &replace(int p0, int n0,const string &s);//删除从p0开始的n0个字符,然后在p0处插入串s
string &replace(int p0, int n0,const string &s, int pos, int n);//删除p0开始的n0个字符,然后在p0处插入串s中从pos开始的n个字符
string &replace(int p0, int n0,int n, char c);//删除p0开始的n0个字符,然后在p0处插入n个字符c
string &replace(iterator first0, iterator last0,const char *s);//把[first0,last0)之间的部分替换为字符串s
string &replace(iterator first0, iterator last0,const char *s, int n);//把[first0,last0)之间的部分替换为s的前n个字符
string &replace(iterator first0, iterator last0,const string &s);//把[first0,last0)之间的部分替换为串s
string &replace(iterator first0, iterator last0,int n, char c);//把[first0,last0)之间的部分替换为n个字符c
string &replace(iterator first0, iterator last0,const_iterator first, const_iterator last);//把[first0,last0)之间的部分替换成[first,last)之间的字符串

로그인 후 복사

string类的插入函数:

string &insert(int p0, const char *s);
string &insert(int p0, const char *s, int n);
string &insert(int p0,const string &s);
string &insert(int p0,const string &s, int pos, int n);
//前4个函数在p0位置插入字符串s中pos开始的前n个字符
string &insert(int p0, int n, char c);//此函数在p0处插入n个字符c
iterator insert(iterator it, char c);//在it处插入字符c,返回插入后迭代器的位置
void insert(iterator it, const_iterator first, const_iterator last);//在it处插入[first,last)之间的字符
void insert(iterator it, int n, char c);//在it处插入n个字符c

로그인 후 복사

string类的删除函数

复制代码 代码如下:
iterator erase(iterator first, iterator last);//删除[first,last)之间的所有字符,返回删除后迭代器的位置
iterator erase(iterator it);//删除it指向的字符,返回删除后迭代器的位置
string &erase(int pos = 0, int n = npos);//删除pos开始的n个字符,返回修改后的字符串

string类的迭代器处理:

string类提供了向前和向后遍历的迭代器iterator,迭代器提供了访问各个字符的语法,类似于指针操作,迭代器不检查范围。
用string::iterator或string::const_iterator声明迭代器变量,const_iterator不允许改变迭代的内容。常用迭代器函数有:

const_iterator begin()const;
iterator begin(); //返回string的起始位置
const_iterator end()const;
iterator end(); //返回string的最后一个字符后面的位置
const_iterator rbegin()const;
iterator rbegin(); //返回string的最后一个字符的位置
const_iterator rend()const;
iterator rend(); //返回string第一个字符位置的前面
rbegin和rend用于从后向前的迭代访问,通过设置迭代器string::reverse_iterator,string::const_reverse_iterator实现

字符串流处理:

通过定义ostringstream和istringstream变量实现,#include 头文件中
例如:

string input("hello,this is a test");
 istringstream is(input);
 string s1,s2,s3,s4;
 is>>s1>>s2>>s3>>s4;//s1="hello,this",s2="is",s3="a",s4="test"
 ostringstream os;
 os<<s1<<s2<<s3<<s4;
 cout<<os.str();

로그인 후 복사

以上就是对C++ string类的一个简要介绍。用的好的话它所具有的功能不会比MFC中的CString类逊色多少,呵呵,个人意见!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 채팅 명령 및 사용 방법
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

C++에서 전략 디자인 패턴을 구현하는 방법은 무엇입니까? C++에서 전략 디자인 패턴을 구현하는 방법은 무엇입니까? Jun 06, 2024 pm 04:16 PM

C++에서 전략 패턴을 구현하는 단계는 다음과 같습니다. 전략 인터페이스를 정의하고 실행해야 하는 메서드를 선언합니다. 특정 전략 클래스를 생성하고 각각 인터페이스를 구현하며 다양한 알고리즘을 제공합니다. 컨텍스트 클래스를 사용하여 구체적인 전략 클래스에 대한 참조를 보유하고 이를 통해 작업을 수행합니다.

C 현에서 숯의 역할은 무엇입니까? C 현에서 숯의 역할은 무엇입니까? Apr 03, 2025 pm 03:15 PM

C에서 숯 유형은 문자열에 사용됩니다. 1. 단일 문자를 저장하십시오. 2. 배열을 사용하여 문자열을 나타내고 널 터미네이터로 끝납니다. 3. 문자열 작동 함수를 통해 작동합니다. 4. 키보드에서 문자열을 읽거나 출력하십시오.

Docker 환경에서 PECL을 사용하여 확장자를 설치할 때 오류가 발생하는 이유는 무엇입니까? 그것을 해결하는 방법? Docker 환경에서 PECL을 사용하여 확장자를 설치할 때 오류가 발생하는 이유는 무엇입니까? 그것을 해결하는 방법? Apr 01, 2025 pm 03:06 PM

Docker 환경을 사용할 때 Docker 환경에 Extensions를 설치하기 위해 PECL을 사용하여 오류의 원인 및 솔루션. 종종 일부 두통이 발생합니다 ...

C-Subscript를 계산하는 방법 3 첨자 5 C-Subscript 3 첨자 5 알고리즘 튜토리얼 C-Subscript를 계산하는 방법 3 첨자 5 C-Subscript 3 첨자 5 알고리즘 튜토리얼 Apr 03, 2025 pm 10:33 PM

C35의 계산은 본질적으로 조합 수학이며, 5 개의 요소 중 3 개 중에서 선택된 조합 수를 나타냅니다. 계산 공식은 C53 = 5입니다! / (3! * 2!)는 효율을 향상시키고 오버플로를 피하기 위해 루프에 의해 직접 계산할 수 있습니다. 또한 확률 통계, 암호화, 알고리즘 설계 등의 필드에서 많은 문제를 해결하는 데 조합의 특성을 이해하고 효율적인 계산 방법을 마스터하는 데 중요합니다.

C 언어로 멀티 스레딩을 구현하는 4 가지 방법 C 언어로 멀티 스레딩을 구현하는 4 가지 방법 Apr 03, 2025 pm 03:00 PM

언어의 멀티 스레딩은 프로그램 효율성을 크게 향상시킬 수 있습니다. C 언어에서 멀티 스레딩을 구현하는 4 가지 주요 방법이 있습니다. 독립 프로세스 생성 : 여러 독립적으로 실행되는 프로세스 생성, 각 프로세스에는 자체 메모리 공간이 있습니다. 의사-다일리트 레딩 : 동일한 메모리 공간을 공유하고 교대로 실행하는 프로세스에서 여러 실행 스트림을 만듭니다. 멀티 스레드 라이브러리 : PTHREADS와 같은 멀티 스레드 라이브러리를 사용하여 스레드를 만들고 관리하여 풍부한 스레드 작동 기능을 제공합니다. COROUTINE : 작업을 작은 하위 작업으로 나누고 차례로 실행하는 가벼운 다중 스레드 구현.

고유 한 기능 사용 거리 함수 C 사용지 자습서 고유 한 기능 사용 거리 함수 C 사용지 자습서 Apr 03, 2025 pm 10:27 PM

STD :: 고유 한 컨테이너의 인접한 중복 요소를 제거하고 끝으로 이동하여 반복자를 첫 번째 중복 요소로 반환합니다. STD :: 거리는 두 반복자 사이의 거리, 즉 그들이 가리키는 요소의 수를 계산합니다. 이 두 기능은 코드를 최적화하고 효율성을 향상시키는 데 유용하지만 : std :: 고유 한 중복 요소를 다루는 것과 같이주의를 기울여야합니다. 비 랜덤 액세스 반복자를 다룰 때는 STD :: 거리가 덜 효율적입니다. 이러한 기능과 모범 사례를 마스터하면이 두 기능의 힘을 완전히 활용할 수 있습니다.

C 언어로 뱀 명칭을 적용하는 방법은 무엇입니까? C 언어로 뱀 명칭을 적용하는 방법은 무엇입니까? Apr 03, 2025 pm 01:03 PM

C 언어에서 뱀 명칭은 코딩 스타일 컨벤션으로 여러 단어를 연결하여 여러 단어를 연결하여 가변 이름 또는 기능 이름을 형성하여 가독성을 향상시킵니다. 편집 및 운영에는 영향을 미치지 않지만 긴 이름 지정, IDE 지원 문제 및 역사적 수하물을 고려해야합니다.

c c Apr 04, 2025 am 07:54 AM

C의 Release_Semaphore 함수는 다른 스레드 또는 프로세스가 공유 리소스에 액세스 할 수 있도록 얻은 수피를 해제하는 데 사용됩니다. 세마포어 수를 1 씩 증가시켜 차단 스레드가 계속 실행 될 수 있습니다.

See all articles