C++ 中的 strchr() 函式


在 C++ 中,strchr() 是一個預定義函式。它用於字串處理,返回給定字串中給定字元的第一次出現。

strchr() 的語法如下。

char *strchr( const char *str, int c)

在上文中,str 是包含字元 c 的字串。strchr() 函式查詢 c 在 str 中的第一次出現。

以下是一個演示 strchr() 函式的程式。

例項

 即時演示

#include <iostream>
#include <cstring>
using namespace std;
int main() {
   char str[] = "strings";
   char * c = strchr(str,'s');
   cout << "First occurrence of character "<< *c <<" in the string is at position "<< c - str + 1;
   return 0;
}

輸出

First occurrence of character s in the string is at position 1

在上面的程式中,首先定義字串 str。然後,指標 c 指向給定字串中字元 s 的第一次出現。這是使用 strchr() 獲得的。s 的位置使用 cout 顯示。所有這些都在以下程式碼片段中給出。

char str[] = "strings";
char * c = strchr(str,'s');
cout << "First occurrence of character "<< *c <<" in the string is at position "<< c - str + 1;

strchr() 函式還可以用來顯示特定字元第一次出現後面的字串,即它可以顯示字串的字尾。以下是一個演示此功能的程式。

例項

 即時演示

#include <iostream>
#include <cstring>
using namespace std;
int main() {
   char str[] = "strings";
   char * c = strchr(str,'i');
   cout << "Remaining string after first occurance of "<< *c <<" is "<< c ;
   return 0;
}

輸出

Remaining string after first occurance of i is ings

在上面的程式中,首先定義字串 str。然後,指標 c 指向給定字串中字元 s 的第一次出現。這是使用 strchr() 獲得的。從 c 指向的位置開始,字串的其餘部分使用 cout 列印。所有這些都在以下程式碼片段中給出。

char str[] = "strings";
char * c = strchr(str,'i');
cout << "Remaining string after first occurance of "<< *c <<" is "<< c ;

更新於: 24-6-2020

360 次瀏覽

開始職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.