C의 문자열에 하위 문자열이 있는지 확인
문자열에 C의 하위 문자열이 포함되어 있는지 확인하려고합니다.
char *sent = "this is my sample example";
char *word = "sample";
if (/* sentence contains word */) {
/* .. */
}
string::find
C ++ 대신 사용할 것이 무엇입니까 ?
if(strstr(sent, word) != NULL) {
/* ... */
}
참고 strstr
로 단어의 시작에 대한 포인터를 반환 sent
단어가있는 경우 word
발견된다.
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)
{
...
}
포인터를 사용해보십시오 ...
#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);
}
하위 문자열의 존재 여부를 찾고이를 추출하여 인쇄하기 위해이 방법을 시도 할 수 있습니다.
#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;
}
이 코드는 기성 함수를 사용하지 않고 검색이 작동하는 방식의 논리를 구현합니다.
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;
}
그리고 찾은 하위 문자열에서 첫 번째 문자의 위치를보고하는 방법은 다음과 같습니다.
위 코드에서이 줄을 바꾸십시오 :
printf("%s",substring,"\n");
와:
printf("substring %s was found at position %d \n", substring,((int) (substring - mainstring)));
내 자신의 겸손한 (대소 문자 구분) 솔루션 :
uint8_t strContains(char* string, char* toFind)
{
uint8_t slen = strlen(string);
uint8_t tFlen = strlen(toFind);
uint8_t found = 0;
if( slen >= tFlen )
{
for(uint8_t s=0, t=0; s<slen; s++)
{
do{
if( string[s] == toFind[t] )
{
if( ++found == tFlen ) return 1;
s++;
t++;
}
else { s -= found; found=0; t=0; }
}while(found);
}
return 0;
}
else return -1;
}
결과
strContains("this is my sample example", "th") // 1
strContains("this is my sample example", "sample") // 1
strContains("this is my sample example", "xam") // 1
strContains("this is my sample example", "ple") // 1
strContains("this is my sample example", "ssample") // 0
strContains("this is my sample example", "samplee") // 0
strContains("this is my sample example", "") // 0
strContains("str", "longer sentence") // -1
strContains("ssssssample", "sample") // 1
strContains("sample", "sample") // 1
ATmega328P (avr8-gnu-toolchain-3.5.4.1709);)에서 테스트
이 간단한 코드에서도 마찬가지입니다.
int main(void)
{
char mainstring[]="The quick brown fox jumps over the lazy dog";
char substring[20];
int i=0;
puts("enter the sub stirng to find");
fgets(substring, sizeof(substring), stdin);
substring[strlen(substring)-1]='\0';
if (strstr(mainstring,substring))
{
printf("substring is present\t");
}
printf("and the sub string is:::");
printf("%s",substring,"\n");
return 0;
}
그러나 까다로운 부분은 원래 문자열에서 하위 문자열이 시작되는 위치를보고하는 것입니다 ...
My code to find out if substring is exist in string or not
// input ( first line -->> string , 2nd lin ->>> no. of queries for substring
following n lines -->> string to check if substring or not..
#include <stdio.h>
int len,len1;
int isSubstring(char *s, char *sub,int i,int j)
{
int ans =0;
for(;i<len,j<len1;i++,j++)
{
if(s[i] != sub[j])
{
ans =1;
break;
}
}
if(j == len1 && ans ==0)
{
return 1;
}
else if(ans==1)
return 0;
return 0;
}
int main(){
char s[100001];
char sub[100001];
scanf("%s", &s);// Reading input from STDIN
int no;
scanf("%d",&no);
int i ,j;
i=0;
j=0;
int ans =0;
len = strlen(s);
while(no--)
{
i=0;
j=0;
ans=0;
scanf("%s",&sub);
len1=strlen(sub);
int value;
for(i=0;i<len;i++)
{
if(s[i]==sub[j])
{
value = isSubstring(s,sub,i,j);
if(value)
{
printf("Yes\n");
ans = 1;
break;
}
}
}
if(ans==0)
printf("No\n");
}
}
나는 가장 간단한 대답이 있다고 생각합니다. 이 프로그램에는 string.h 라이브러리 나 stdbool.h 라이브러리가 필요하지 않습니다. 포인터와 포인터 산술을 사용하면 더 나은 C 프로그래머가 될 수 있습니다.
False (하위 문자열을 찾을 수 없음)의 경우 0을, True (예 : 하위 문자열 "sub"가 전체 문자열 "str"내에 있음) 인 경우 1을 반환합니다.
#include <stdlib.h>
int is_substr(char *str, char *sub)
{
int num_matches = 0;
int sub_size = 0;
// If there are as many matches as there are characters in sub, then a substring exists.
while (*sub != '\0') {
sub_size++;
sub++;
}
sub = sub - sub_size; // Reset pointer to original place.
while (*str != '\0') {
while (*sub == *str && *sub != '\0') {
num_matches++;
sub++;
str++;
}
if (num_matches == sub_size) {
return 1;
}
num_matches = 0; // Reset counter to 0 whenever a difference is found.
str++;
}
return 0;
}
#include <stdio.h>
#include <string.h>
int findSubstr(char *inpText, char *pattern);
int main()
{
printf("Hello, World!\n");
char *Text = "This is my sample program";
char *pattern = "sample";
int pos = findSubstr(Text, pattern);
if (pos > -1) {
printf("Found the substring at position %d \n", pos);
}
else
printf("No match found \n");
return 0;
}
int findSubstr(char *inpText, char *pattern) {
int inplen = strlen(inpText);
while (inpText != NULL) {
char *remTxt = inpText;
char *remPat = pattern;
if (strlen(remTxt) < strlen(remPat)) {
/* printf ("length issue remTxt %s \nremPath %s \n", remTxt, remPat); */
return -1;
}
while (*remTxt++ == *remPat++) {
printf("remTxt %s \nremPath %s \n", remTxt, remPat);
if (*remPat == '\0') {
printf ("match found \n");
return inplen - strlen(inpText+1);
}
if (remTxt == NULL) {
return -1;
}
}
remPat = pattern;
inpText++;
}
}
참고 URL : https://stackoverflow.com/questions/12784766/check-substring-exists-in-a-string-in-c
'Programming' 카테고리의 다른 글
List 유형의 속성을 유지하는 방법 (0) | 2020.06.15 |
---|---|
루비 수면 또는 1 초 미만 지연? (0) | 2020.06.15 |
C ++의 dynamic_cast 및 static_cast (0) | 2020.06.13 |
기본 HTML / CSS 링크 색상은 무엇입니까? (0) | 2020.06.13 |
ActiveRecord 속성 메소드 대체 (0) | 2020.06.13 |