logo

C++ String Find()

Ta funkcija se uporablja za iskanje določenega podniza.

Sintaksa

Razmislite o dveh nizih str1 in str2. Sintaksa bi bila:

 str1.find(str2); 

Parametri

str: Niz, ki ga je treba iskati.

položaj: Določa položaj znaka, pri katerem se začne iskanje.

n: Število znakov v nizu za iskanje.

ch: Določa znak za iskanje.

Povratna vrednost

Vrne položaj prvega znaka prvega ujemanja.

Primer 1

Poglejmo preprost primer.

 #include using namespace std; int main() { string str= &apos;java is the best programming language&apos;; cout &lt;&lt; str&lt;<'
'; cout <<' position of the programming word is :'; cout<< str.find('programming'); return 0; } < pre> <p> <strong>Output:</strong> </p> <pre> Java is the best programming language Position of the programming word is 17 </pre> <h2>Example 2</h2> <p>Let&apos;s see simple example by passing position of a character as a parameter.</p> <pre> #include using namespace std; int main() { string str= &apos;Mango is my favorite fruit&apos;; cout &lt;&lt; str&lt;<'
'; cout<< ' position of fruit is :'; str.find('fruit',12); return 0; } < pre> <p> <strong>Output:</strong> </p> <pre> Mango is my favorite fruit Position of fruit is 21 </pre> <h2>Example 3</h2> <p>Let&apos;s see simple example of finding a single character.</p> <pre> #include using namespace std; int main() { string str = &apos;javatpoint&apos;; cout &lt;&lt; &apos;String contains :&apos; &lt;&lt; str; cout&lt;&lt; &apos;position of p is :&apos; &lt;&lt; str.find(&apos;p&apos;); return 0; } </pre> <p> <strong>Output:</strong> </p> <pre> String contains : javatpoint Position of p is 5 </pre> <br></'
';></pre></'
';>

Primer 2

Oglejmo si preprost primer s posredovanjem položaja znaka kot parametra.

 #include using namespace std; int main() { string str= &apos;Mango is my favorite fruit&apos;; cout &lt;&lt; str&lt;<\'
\'; cout<< \' position of fruit is :\'; str.find(\'fruit\',12); return 0; } < pre> <p> <strong>Output:</strong> </p> <pre> Mango is my favorite fruit Position of fruit is 21 </pre> <h2>Example 3</h2> <p>Let&apos;s see simple example of finding a single character.</p> <pre> #include using namespace std; int main() { string str = &apos;javatpoint&apos;; cout &lt;&lt; &apos;String contains :&apos; &lt;&lt; str; cout&lt;&lt; &apos;position of p is :&apos; &lt;&lt; str.find(&apos;p&apos;); return 0; } </pre> <p> <strong>Output:</strong> </p> <pre> String contains : javatpoint Position of p is 5 </pre> <br></\'
\';>

Primer 3

Oglejmo si preprost primer iskanja enega znaka.

 #include using namespace std; int main() { string str = &apos;javatpoint&apos;; cout &lt;&lt; &apos;String contains :&apos; &lt;&lt; str; cout&lt;&lt; &apos;position of p is :&apos; &lt;&lt; str.find(&apos;p&apos;); return 0; } 

Izhod:

 String contains : javatpoint Position of p is 5