Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

40,011 questions

51,958 answers

573 users

How to check if a string starts and ends with another string in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
 
char *get_substring(char *s, int start_point, int sub_len) {
    char *sub = (char *)malloc((sub_len * sizeof(char)) + 1);
	
	for (int i = start_point, j = 0; i < (start_point + sub_len); i++, j++) {
		sub[j] = s[i];
	}
    sub[sub_len] = '\0';
    
	return sub;
}
 
bool string_start_and_end_match(char s[], char match[]) { 
    int s_len = strlen(s); 
    int match_len = strlen(match); 
 
    if (s_len < match_len) 
       return false; 
   
	char *sub_start = get_substring(s, 0, match_len);
	char *sub_end = get_substring(s, s_len - match_len, match_len);

	bool b = false;
	
	if (strcmp(sub_start, match) == 0 && strcmp(sub_end, match) == 0)
		b = true;
	
	free(sub_start);
	free(sub_end);
	
	return b;
} 

int main() 
{                       
    char s[] = "c c++ php python c c++"; 
    char match[] = "c c++"; 
    
    if (string_start_and_end_match(s, match))
        puts("yes");
    else
        puts("no");
     
    return 0; 
} 


  
/*
run:
  
yes
  
*/

 



answered Nov 14, 2019 by avibootz

Related questions

...