English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Esempio di codice di ricerca e abbinamento della stringa C++

In una programmazione C++, si incontra sempre la situazione di cercare una piccola substring in una stringa. Per C, spesso si utilizzano strstr() o strchr(). Per la stringa C++, spesso si utilizza find().

C++: #inlcude<string>
C: #include<string.h>

find():Ricerca di un singolo carattere specificato o di un array di caratteri in una stringa. Se trovato, restituisce la posizione di inizio della prima corrispondenza; se non viene trovato alcun contenuto corrispondente, restituisce string::npos.

find_first_of():Ricerca in una stringa di destinazione, il valore restituito è la posizione del primo carattere che corrisponde a qualsiasi carattere del gruppo di caratteri specificato. Se non viene trovato alcun contenuto corrispondente, viene restituito npos.

find_last_of():Ricerca in una stringa di destinazione, restituisce la posizione del carattere più recente che corrisponde a qualsiasi carattere del gruppo di caratteri specificato. Se non viene trovato alcun contenuto corrispondente, viene restituito npos.

find_first_not_of():Search within a target string and return the position of the first element that does not match any character in the specified character group. If no such element is found, return npos.

find_last_not_of():Search within a target string and return the position of the largest element that does not match any character in the specified character group. If no such element is found, return npos.

rfind(): Search for a specified single character or character group from the end of a string. If found, return the starting position of the first match; if not found, return npos.

find(string, int):The first parameter is used to indicate the character to be searched, and the second parameter is used to indicate from where to start searching for the substring in the string (the default search position is 0).

Example: string matching:

#include "stdafx.h"
#include<iostream>
#include<math.h>
#include<string>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
string T;//original string
string P;//pattern
while(cin>>T>>P)
{ 
int count=0;
int begin=-1;
while((begin=T.find(P,begin+1))!=string::npos)
{
count++;
}
cout<<count<<endl;
}
int z;
cin>>z;
return 0;
}

This is the full content of the C++ string string search and match example code brought to you by the editor. I hope everyone will support and cheer for the tutorial~

Ti potrebbe interessare