473,811 Members | 3,736 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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<iostre am>
#include<cstrin g>
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(str 1); //determine the lengths of the strings
len2=strlen(str 2);
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 8589

"Radhika Sambamurti" <ra*****@schema mania.org> wrote in message
news:2004022015 2353.3c0d3e87.r a*****@schemama nia.org...
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_o f( )
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<iostre am>
#include<cstrin g>
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(str 1); //determine the lengths of the strings
len2=strlen(str 2);
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(str 1); //determine the lengths of the strings
len2=strlen(str 2);
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********@boe ing.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::np os, not -1.
Jul 22 '05 #7
Radhika Sambamurti wrote:

On Fri, 20 Feb 2004 22:16:39 GMT
Default User <fi********@boe ing.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
6397
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 arounds to no avail, am I defining the two string variable incorrectly? code snippet: String lastChar = new String();
62
31932
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 position of a substring in a string? Thx a lot...
6
22760
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? // Remove (first occurence of) sub from src void func(char *src, char *sub) { char *p;
11
5363
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 (strIn.Substring(410, 10).Trim = "") Then 'Something processed Else 'Something processed
2
2028
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
51757
by: Ajay | last post by:
Hi all,Could anybody tell me the most efficient method to find a substr in a string.
2
3182
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 a tasty burger"
6
9274
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 = "kelly" with no error // but string s2 = "kelly".Substring(0,200) // results in // ArgumentOutOfRangeException
7
4232
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 get an error saying that the I have an Invalid column 'Course_Number'. Not sure why but I am very new to User Defined Functions. Here is what I have so far: CREATE FUNCTION CourseEvalBreakdown (
0
9731
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10651
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10393
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10405
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10136
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7671
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6893
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5556
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5697
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.