我正在尝试检查字符串是否包含C中的子字符串,如:
char *sent = "this is my sample example";
char *word = "sample";
if (/* sentence contains word */) {
/* .. */
}
Run Code Online (Sandbox Code Playgroud)
什么是使用而不是string::find
在C++中?
nne*_*neo 242
if(strstr(sent, word) != NULL) {
/* ... */
}
Run Code Online (Sandbox Code Playgroud)
请注意,如果找到strstr
单词,sent
则返回指向单词开头的指针word
.
Tan*_*avo 30
使用strstr
此.
http://www.cplusplus.com/reference/clibrary/cstring/strstr/
所以,你会写它...
char *sent = "this is my sample example";
char *word = "sample";
char *pch = strstr(sent, word);
if(pch)
{
...
}
Run Code Online (Sandbox Code Playgroud)
Jus*_*lly 11
尝试使用指针......
#include <stdio.h>
#include <string.h>
int main()
{
char str[] = "String1 subString1 Strinstrnd subStr ing1subString";
char sub[] = "subString";
char *p1, *p2, *p3;
int i=0,j=0,flag=0;
p1 = str;
p2 = sub;
for(i = 0; i<strlen(str); i++)
{
if(*p1 == *p2)
{
p3 = p1;
for(j = 0;j<strlen(sub);j++)
{
if(*p3 == *p2)
{
p3++;p2++;
}
else
break;
}
p2 = sub;
if(j == strlen(sub))
{
flag = 1;
printf("\nSubstring found at index : %d\n",i);
}
}
p1++;
}
if(flag==0)
{
printf("Substring NOT found");
}
return (0);
}
Run Code Online (Sandbox Code Playgroud)
小智 6
您可以尝试使用此方法查找子字符串的存在并提取并打印它:
#include <stdio.h>
#include <string.h>
int main(void)
{
char mainstring[]="The quick brown fox jumps over the lazy dog";
char substring[20], *ret;
int i=0;
puts("enter the sub string to find");
fgets(substring, sizeof(substring), stdin);
substring[strlen(substring)-1]='\0';
ret=strstr(mainstring,substring);
if(strcmp((ret=strstr(mainstring,substring)),substring))
{
printf("substring is present\t");
}
printf("and the sub string is:::");
for(i=0;i<strlen(substring);i++)
{
printf("%c",*(ret+i));
}
puts("\n");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这段代码实现了搜索工作原理的逻辑(一种方式),而无需使用任何现成的函数:
public int findSubString(char[] original, char[] searchString)
{
int returnCode = 0; //0-not found, -1 -error in imput, 1-found
int counter = 0;
int ctr = 0;
if (original.Length < 1 || (original.Length)<searchString.Length || searchString.Length<1)
{
returnCode = -1;
}
while (ctr <= (original.Length - searchString.Length) && searchString.Length > 0)
{
if ((original[ctr]) == searchString[0])
{
counter = 0;
for (int count = ctr; count < (ctr + searchString.Length); count++)
{
if (original[count] == searchString[counter])
{
counter++;
}
else
{
counter = 0;
break;
}
}
if (counter == (searchString.Length))
{
returnCode = 1;
}
}
ctr++;
}
return returnCode;
}
Run Code Online (Sandbox Code Playgroud)