473,241 Members | 1,890 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,241 software developers and data experts.

substring function

Hi,
I've written a substring function.
The prototype is: int substr(char s1[], char s2[])
Returns 1 if s2 is a substring of s1, else it returns 0.
I have written this program, but Im sure there is an easier way to do this. I am hoping someone can point me to a more elegant way of writing this same function.

//// code follows ///////////

//implement a substring function, where if string2 is a sub of string 1, then the value returned is 1 else, 0

#include<iostream>
#include<cstring>
using namespace std;

const int MAX = 10;
int substring(char *str1, char *str2); //prototype

int main()
{
char response = 'y';
char str1[MAX];
char str2[MAX];
int result = 0;

while(response == 'Y' || response == 'y')
{
cout << "Please enter string 1: " ;
cin >> str1;

cout << "\nPlease enter string 2: ";
cin >> str2;

cout << endl;

result = substring(str1, str2); //function call

if(result == 1)
cout << "string " << str2 << " is a substring of " << str1 << endl;
else
cout << "string " << str2 << " is NOT a substring of " << str1 << endl;

cout << "would you like to enter another? (Y/N) " << endl;
cin >> response;

}

return 0;
}

//''''''''''''''''''''''''''''''''''''''''''
//Function definition substring

int substring(char *str1, char *str2)
{
int len1, len2, i=0, j = 0, k, n;
len1=strlen(str1); //determine the lengths of the strings
len2=strlen(str2);
while(i <len1)
{

while( str2[j] == str1[i] )
{

for(k=1, n=i+1; k<len2; k++, n++)

//n is assigned i, which is where the match //starts in string 1- starting at the next letter

{
if( str2[k] != str1[n] )
return 0; //the match fails after having made an initial match
}
return 1;

j++;
}

i++;
}
}


Jul 22 '05 #1
7 8546

"Radhika Sambamurti" <ra*****@schemamania.org> wrote in message
news:20040220152353.3c0d3e87.ra*****@schemamania.o rg...
Hi,
I've written a substring function.
The prototype is: int substr(char s1[], char s2[])
Returns 1 if s2 is a substring of s1, else it returns 0.
I have written this program, but Im sure there is an easier way to do this. I am hoping someone can point me to a more elegant way of writing this
same function.


Why not use the std::string member functions?

find( )
find_first_of( )
find_last_of( )
find_first_not_of( )
find_last_not_of( )
rfind( )

These return the starting position of the where the match is found, or a -1
cast to unsigned int if no match is found.
Jul 22 '05 #2
How about this:

int substring(char *str1, char *str2)
{
return (strstr(str1, str2) != NULL);
}

-jj-

Radhika Sambamurti wrote:

Hi,
I've written a substring function.
The prototype is: int substr(char s1[], char s2[])
Returns 1 if s2 is a substring of s1, else it returns 0.
I have written this program, but Im sure there is an easier way to do this. I am hoping someone can point me to a more elegant way of writing this same function.

//// code follows ///////////

//implement a substring function, where if string2 is a sub of string 1, then the value returned is 1 else, 0

#include<iostream>
#include<cstring>
using namespace std;

const int MAX = 10;
int substring(char *str1, char *str2); //prototype

int main()
{
char response = 'y';
char str1[MAX];
char str2[MAX];
int result = 0;

while(response == 'Y' || response == 'y')
{
cout << "Please enter string 1: " ;
cin >> str1;

cout << "\nPlease enter string 2: ";
cin >> str2;

cout << endl;

result = substring(str1, str2); //function call

if(result == 1)
cout << "string " << str2 << " is a substring of " << str1 << endl;
else
cout << "string " << str2 << " is NOT a substring of " << str1 << endl;

cout << "would you like to enter another? (Y/N) " << endl;
cin >> response;

}

return 0;
}

//''''''''''''''''''''''''''''''''''''''''''
//Function definition substring

int substring(char *str1, char *str2)
{
int len1, len2, i=0, j = 0, k, n;
len1=strlen(str1); //determine the lengths of the strings
len2=strlen(str2);
while(i <len1)
{

while( str2[j] == str1[i] )
{

for(k=1, n=i+1; k<len2; k++, n++)

//n is assigned i, which is where the match //starts in string 1- starting at the next letter

{
if( str2[k] != str1[n] )
return 0; //the match fails after having made an initial match
}
return 1;

j++;
}

i++;
}
}



Jul 22 '05 #3
Radhika Sambamurti wrote:

Hi,
I've written a substring function.
The prototype is: int substr(char s1[], char s2[])
Returns 1 if s2 is a substring of s1, else it returns 0.

Why? Is this for a school exercise, or self-teaching? The above function
is almost, but not quite, the same as the C standard function strstr().

Why even mess with C-style strings?
I have written this program, but Im sure there is an easier way to do this. I am hoping someone can point me to a more elegant way of writing this same function.
int substr(char s1[], char s2[])
{
if (strstr (s1, s2))
return 1;
return 0;
}

;)
int substring(char *str1, char *str2)
{
int len1, len2, i=0, j = 0, k, n;
len1=strlen(str1); //determine the lengths of the strings
len2=strlen(str2);
These calls to strlen() are going to whack your efficiency. They
terminate C-style strings for a reason, use that in your routine. You
don't need to know the lengths, just the endpoints.

while(i <len1)
{

while( str2[j] == str1[i] )
{

for(k=1, n=i+1; k<len2; k++, n++)

//n is assigned i, which is where the match //starts in string 1- starting at the next letter

{
if( str2[k] != str1[n] )
return 0; //the match fails after having made an initial match
}
return 1;

j++;
}

i++;
}
}


Here's one to consider:
int substr(const char *string, const char *substring)
{
const char *a = string;
const char *b = substring;

b = substring;
if (*b == 0)
{
return 1;
}
for ( ; *string != 0; string += 1)
{
if (*string != *b)
{
continue;
}
while (1)
{
if (*b == 0)
{
return 1;
}
if (*a++ != *b++)
{
break;
}
}
}
return 0;
}
Brian Rodenborn
Jul 22 '05 #4
Default User wrote:
int substr(const char *string, const char *substring)
{
const char *a = string;
const char *b = substring;

b = substring;


The above line is superfluous and should have been removed when I move
the assignments up to initializers.
Sorry.


Brian Rodenborn
Jul 22 '05 #5

On Fri, 20 Feb 2004 22:16:39 GMT
Default User <fi********@boeing.com.invalid> wrote:
Radhika Sambamurti wrote:

Hi,
I've written a substring function.
The prototype is: int substr(char s1[], char s2[])
Returns 1 if s2 is a substring of s1, else it returns 0.

Why? Is this for a school exercise, or self-teaching? The above function
is almost, but not quite, the same as the C standard function strstr().

Thanks! Yes, this was a class exercise.

Jul 22 '05 #6

These return the starting position of the where the match is found, or a -1
cast to unsigned int if no match is found.


I know that this is practically irrelevant, but the correct return value
is std::string::npos, not -1.
Jul 22 '05 #7
Radhika Sambamurti wrote:

On Fri, 20 Feb 2004 22:16:39 GMT
Default User <fi********@boeing.com.invalid> wrote:
Radhika Sambamurti wrote:

Hi,
I've written a substring function.
The prototype is: int substr(char s1[], char s2[])
Returns 1 if s2 is a substring of s1, else it returns 0.

Why? Is this for a school exercise, or self-teaching? The above function
is almost, but not quite, the same as the C standard function strstr().

Thanks! Yes, this was a class exercise.


Ok. What you had wasn't too bad, although much more appropriate for a C
class than C++. I'm suspicious of the quality of instruction you are
getting.


Brian Rodenborn
Jul 22 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: Don Freeman | last post by:
Seems like whatever value I use for the first int field (starting position) the substring procedure negates it and triggers a String index out of range error. I've tried all sorts of work...
62
by: Jupiter | last post by:
Hey, I would like to know 2 things. 1)Is there any function (in C standard library) that extracts a substring from a string? 2)Is there any function (in C standard library) that returns the...
6
by: becte | last post by:
I am little bit confused Is this a legal way of removing a substring from a string? What about the second alternative using strcpy, is it ok even though the source and dest. strings overlap? ...
11
by: Darren Anderson | last post by:
I have a function that I've tried using in an if then statement and I've found that no matter how much reworking I do with the code, the expected result is incorrect. the code: If Not...
2
by: David Filion | last post by:
Hi, I have a question about substring(), when I run the following query: prepaid=# select substring('15148300', 0, 5); substring ----------- 1514 (1 row)
29
by: Ajay | last post by:
Hi all,Could anybody tell me the most efficient method to find a substr in a string.
2
by: Badass Scotsman | last post by:
Hello, Using VB and ASP,NET I would like to be able to search a STRING for a smaller STRING within, based on the characters which appear before and after. For example: String1 = " That was...
6
by: kellygreer1 | last post by:
What is a good one line method for doing a "length safe" String.Substring? The VB classes offer up the old Left function so that string s = Microsoft.VisualBasic.Left("kelly",200) // s will =...
7
by: jknaty | last post by:
I'm trying to create a function that splits up a column by spaces, and I thought creating a function that finds the spaces with CHARINDEX and then SUBSTRING on those values would an approach. I...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.