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

Home Posts Topics Members FAQ

substring

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...
Nov 13 '05 #1
62 31932

"Jupiter" <ze******@yahoo .com> wrote in message
news:27******** *************** ***@posting.goo gle.com...
Hey,
I would like to know 2 things.
1)Is there any function (in C standard library) that extracts a
substring from a string? Not directly -- this has to be emulated with a more general
function such as memcpy (how exactly depends on the
destination storage for the substring).
2)Is there any function (in C standard library) that returns the
position of a substring in a string?

Yes:
char* pos = strstr(str_to_s earch_through,s tr_to_find);
(null if not found).

hth, Ivan
--
http://ivan.vecerina.com
Nov 13 '05 #2
"Jupiter" <ze******@yahoo .com> wrote in message
news:27******** *************** ***@posting.goo gle.com...
Hey,
I would like to know 2 things.
1)Is there any function (in C standard library) that extracts a
substring from a string?
Yes.
2)Is there any function (in C standard library) that returns the
position of a substring in a string?
Yes.
Thx a lot...


The questions you presumably *wanted* to ask were "what is the function
to..." :-)

To extract a substring on positions n to m from a string s you can use

strncpy(dest, s + n, m - n + 1);
dest[m - n] = 0;

(or in short strncpy(dest, s + n, m - n + 1)[m - n] = 0;)

Look up strncpy in your manual to see how it works and why adding the
zero is necessary. You must also make sure beforehand that:
a) s is at leat n + 1 characters long and
b) you have enough space in dest for m - n + 1 characters.

To find a substring in a string you can use

char * position = strstr(substrin g, string);

If you want an offset rather than a pointer to the substring, use

size_t offset = position - string;

Again, look up strstr in your manual for reference. Please note that
strstr returns NULL if the substring is not foud in string, you must
check for that.
Nov 13 '05 #3

"Peter Pichler" <pi*****@pobox. sk> wrote in message
news:UO******** *******@newsfep 1-gui.server.ntli .net...
To find a substring in a string you can use

char * position = strstr(substrin g, string); .... Again, look up strstr in your manual for reference.


Err, *I* should have looked up strstr in the manual. Swap the two
parameters around. Doh!
Nov 13 '05 #4
In article <27************ **************@ posting.google. com>, Jupiter wrote:
Hey,
I would like to know 2 things.
1)Is there any function (in C standard library) that extracts a
substring from a string?
Yes, strncpy() can be made to copy a substring of one string
into another:

#include <string.h> /* for strncpy() */
#include <stdio.h> /* for printf() */

int
main(void)
{
char msg[] = "Hello World!";
char submsg[10]; /* Must be long enough */

/* Copy the substring "o W" from msg to submsg */
strncpy(submsg, &msg[4], 3);

/* Terminate the resulting string since strncpy() doesn't */
submsg[3] = '\0';

printf("msg[] = '%s'\nsubmsg[] = '%s'\n", msg, submsg);

return 0;
}

2)Is there any function (in C standard library) that returns the
position of a substring in a string?
No, but you may use strstr() like this:

#include <string.h> /* for strstr() */
#include <stdio.h> /* for printf(), fprintf() */
#include <stddef.h> /* for ptrdiff_t, NULL */

int
main(void)
{
char msg[] = "Hello World!";
char *ptr;

ptrdiff_t ptrpos;

/* Locate the substring "o W" in msg */
ptr = strstr(msg, "o W");

if (ptr == NULL) {
fprintf(stderr, "Substring not found\n");
} else {
/* Calculate the position of ptr in msg */
ptrpos = ptr - &msg[0];

printf("Positio n of 'o W' in '%s' is %d\n", msg, ptrpos);
}

return 0;
}

Thx a lot...


Wlcm a lot...
--
Andreas Kähäri
Nov 13 '05 #5


Jupiter wrote:
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?


Yes. Take a look at http://www-ccs.ucsd.edu/c/string.html for a list of
the string functions in string.h. Buying a copy of K&R 2 wouldn't be a
bad idea either...

Ed.

Nov 13 '05 #6
Greetings.

In article <3f********@new s.swissonline.c h>, Ivan Vecerina wrote:
1)Is there any function (in C standard library) that extracts a
substring from a string?


Not directly -- this has to be emulated with a more general
function such as memcpy (how exactly depends on the
destination storage for the substring).


Eh? You got something against strncpy() or something?

--
_
_V.-o Tristan Miller [en,(fr,de,ia)] >< Space is limited
/ |`-' -=-=-=-=-=-=-=-=-=-=-=-=-=-=-= <> In a haiku, so it's hard
(7_\\ http://www.nothingisreal.com/ >< To finish what you
Nov 13 '05 #7


Tristan Miller wrote:
Greetings.

In article <3f********@new s.swissonline.c h>, Ivan Vecerina wrote:
1)Is there any function (in C standard library) that extracts a
substring from a string?


Not directly -- this has to be emulated with a more general
function such as memcpy (how exactly depends on the
destination storage for the substring).

Eh? You got something against strncpy() or something?


'Something' might be more appropriate than strncpy. It depends on
the definition of 'extract'. I interpret this to mean to remove a
substring from a string.

Take string:
char s[] = "Have a very good day"
and extract the substring "very " to make s the
string "Have a good day".

If this is the intent of the OP, then a solution would not involve
strncpy or memcpy. A function duo of strstr and memmove would
do the job.

--
Al Bowers
Tampa, Fl USA
mailto: xa******@myrapi dsys.com (remove the x to send email)
http://www.geocities.com/abowers822/

Nov 13 '05 #8
Tristan Miller wrote:
Greetings.

In article <3f********@new s.swissonline.c h>, Ivan Vecerina wrote:
1)Is there any function (in C standard library) that extracts a
substring from a string?


Not directly -- this has to be emulated with a more general
function such as memcpy (how exactly depends on the
destination storage for the substring).


Eh? You got something against strncpy() or something?


Well, as a substring extractor, it's suboptimal.

Consider, for example:

char foo[16];
char bar[16] = "abcdefghijklmn o";

strncpy(foo, bar, 3);

At the end of this operation, foo does not contain a string. Oops.

--
Richard Heathfield : bi****@eton.pow ernet.co.uk
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton
Nov 13 '05 #9
Greetings.

In article <bo**********@h ercules.btinter net.com>, Richard Heathfield wrote:
Consider, for example:

char foo[16];
char bar[16] = "abcdefghijklmn o";

strncpy(foo, bar, 3);

At the end of this operation, foo does not contain a string. Oops.


Well, it doesn't contain a nul-terminated string, but it does contain the
first three characters of bar, which may be all that is needed in some
cases. Does the C standard use the term "string" to refer to both nul- and
non-nul-terminated strings, or does it make a nomenclatural distinction
between "string" (which always includes the sentinel) and the more general
"array-of-char"?

--
_
_V.-o Tristan Miller [en,(fr,de,ia)] >< Space is limited
/ |`-' -=-=-=-=-=-=-=-=-=-=-=-=-=-=-= <> In a haiku, so it's hard
(7_\\ http://www.nothingisreal.com/ >< To finish what you
Nov 13 '05 #10

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();
7
8589
by: Radhika Sambamurti | last post by:
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...
1
8112
by: sysindex | last post by:
I am trying to find a way to dynamically retrieve the substring starting point of an nText field. My query looks something like SELECT ID,Substring(DOCTEXT,0,200) from mytable where DOCTEXT like 'claim%'" This query has substring starting point set to 0. Is there a way to determine the starting point based on the first occurrence of the
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
5
2938
by: btober | last post by:
I can't seem to get right the regular expression for parsing data like these four sample rows (names and addresses changed to ficticious values) from a text-type column: Yolanda Harris, 38, of 40 South Main St., Newtown City, was charged Sunday with breach of peace and interfering with a police officer. Allen K. George, 30, of 88 Beverly Court was charged Saturday with possession of marijuana, third-degree criminal mischief, breach of...
2
6417
by: mallard134 | last post by:
Could someone please help a newbee vb programmer with a question that is driving me crazy. I am trying to understand a line of code that is supposed to return the domain portion of a valid email address. The following code works! ****************************************************************** strEmail = "j...@mydomain.com" String2 = strEmail.Substring(strEmail.IndexOf("@") + 1, _
4
3265
by: Jean-François Michaud | last post by:
Hello, I've been looking at this for a bit now and I don't see what's wrong with the code. Can anybody see a problem with this? Here is an XSLT snippet I use. <xsl:template match="graphic"> <xsl:param name="path" /> <fo:block padding-after="12pt">
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
11
7058
by: dyc | last post by:
how do i make use of substring method in order to extract the specified data from a a long string? I also need to do some checking b4 extracting the data, for instance: it only will extract the data when the first 8bits are 10101010,then it ll extract the following...for example: 10101010111000111 here is my code: Dim dataE As String Dim lot101, lot102, lot103, lot104 As String
3
2591
by: =?Utf-8?B?anAybXNmdA==?= | last post by:
Two part question: 1. Is Regex more efficient than manually comparing values using Substring? 2. I've never created a Regex expression. How would I use regex to do the equivalent of what I have coded using Substrings below? string s = TextBox1.Text.ToUpper(); string ch = s.Substring(0, 1); // read first character if ((ch == "B") || (ch == "C") || (ch == "X")) {
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
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...
0
9208
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
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?
3
3020
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.