C++中的函数(STRCR)及其应用

在C++中,StrrRy.()是一种预定义函数,用于查找字符串中字符的出现。它存在于cstring头文件中。

null

语法

// Returns pointer to the first occurrence// of c in str[]char *strchr(const char *str, int c) 

请注意,c作为其int升级传递,但它在内部被视为char。 应用 给定C++中的字符串,我们需要找到字符的第一个出现,让我们说“A”。

例如:

Input : str[] = 'This is a string'Output : 9Input : str[] = 'My name is Ayush'Output : 5

算法 1.在strchr()函数中传递给定的字符串,并指出需要指向的字符。 2.函数返回值,打印值。

以下是上述算法的实现:

CPP

// CPP program to find position of a character
// in a given string.
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char str[] = "My name is Ayush" ;
char * ch = strchr (str, 'a' );
cout << ch - str + 1;
return 0;
}


输出

5

strchr() 函数还可用于检查字符串中是否存在字符。输入由一个我们想要检查的字符组成,如果它存在于字符串中。 例如,让我们检查字符串中是否存在字符A和z——“我的名字是Ayush”

Input : str[] = 'My name is Ayush',         ch1 = 'A', ch2 = 'z'Output : A is present in the string         z is not present in the string

算法 1.将给定字符串作为第二个参数传递到strchr()函数中,并检查返回的值是否为null 2.如果函数返回空值,这意味着字符串不包含字符,因此,请打印所需的语句。 3.否则,如果函数不返回空值,这意味着字符串包含字符,因此,请打印所需的语句。

以下是上述算法的实现:

CPP

// CPP program to demonstrate working of strchr()
#include <iostream>
#include <cstring>
using namespace std;
// Driver code
int main()
{
char str[] = "My name is Ayush" ;
char ch = 'A' , ch2 = 'z' ;
if ( strchr (str, ch) != NULL)
cout << ch << " "
<< "is present in string" << endl;
else
cout << ch << " "
<< "is not present in string" << endl;
if ( strchr (str, ch2) != NULL)
cout << ch2 << " "
<< "is present in string" << endl;
else
cout << ch2 << " "
<< "is not present in string" << endl;
return 0;
}


输出:

A is present in stringz is not present in string

函数可用于查找Linux的绝对目录路径: (作者: 埃克塔努内瓦尔 )

例如:

Input : /home/test/sampleOutput : /home/test

算法:

  1. 使用strrchr查找目录路径中最后一个“/”的位置。
  2. 将出现的内容替换为空字符。

以下是上述算法的实现:

C

// C program to find directory path
#include <string.h>
#include<stdio.h>
int main()
{
char string[]={ "/home/test/sample" };
int len;
//position of last char
char * pos;
// save length of string
len = strlen (string);
// Find the last character with
pos = strrchr (string, '/' ) ;
printf ( "%s" ,string);
// replace last occurrence of / with NULL character.
*pos= ' ' ;
printf ( "%s" ,string);
return 0;
}


输出

/home/test/sample

本文由 阿尤什·萨克塞纳 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享