473,882 Members | 1,663 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Getting the middle of a string

I've tried to make a function that returns the middle of a string. For
example:
strmid("this is a text",6,4); would return "is a".

Here is my code:
char *strmid(char *texte, int depart, int longueur)
{ char *resultat = " ";
char *temporaire = " ";
int nbr;

nbr = depart + longueur - 1;

strncat(tempora ire,texte,nbr);
strrev(temporai re);
strncat(resulta t,temporaire,lo ngueur+1);
strrev(resultat );

return resultat;
}
It doesn't work properly, but I really don't understand why. Can anyone
enlighten me? Or, if there's a similar code that works already, can I have
it please?

Thanks,
- A new C programmer
Nov 13 '05
17 14380
In article <3F***********@ earthlink.net>, jo********@eart hlink.net says...
#define LEN 256

char *substr(char *string, int start, size_t count) {
static char str[LEN];
[...]
return str;
}


<sarcasm>
Which is real damn useful if you try to do the following:

char a = substr ("This is a string", 6, 4);
char b = substr (a, 2, 1);
printf ("<%s>, <%s>\n", a, b);

</sarcasm>

--
Paul Hsieh
http://www.pobox.com/~qed/
http://bstring.sf.net/
Nov 13 '05 #11
Paul Hsieh wrote:
[snip...] Which requires that you have made sufficient space in the variable resultat.
The problem is that simply declaring resultat = " " somewhere in your
code is not good enough, since all the space for resultat may be allocated in
non-writable memory. If you want to avoid this issue you can automatically
make writable memory available:

char *strmid (const char *texte, int depart, int longueur) {
char *resultat = (char *) malloc (longueur + 1);
memmove (resultat, texte + depart, longueur);
resultat[longueur] = '\0';
return resultat;
}


Casting the result of a malloc() is considered bad practice by most
knowledgable C programmers, including the vast majority of the regulars
here.

Best regards,

Sidney

Nov 13 '05 #12
Olivier Bellemare wrote:

I've tried to make a function that returns the middle of a string.
For example:
strmid("this is a text",6,4); would return "is a".
I would expect it to return "s a ", if anything.

Here is my code:
char *strmid(char *texte, int depart, int longueur)
{ char *resultat = " ";
This is a pointer to a string holding one blank, which cannot be
altered. Seems fairly useless here.
char *temporaire = " ";
This is a pointer to a string holding one blank, which cannot be
altered. Seems fairly useless here.
int nbr;

nbr = depart + longueur - 1;

strncat(tempora ire,texte,nbr);
strrev(temporai re);
This function does not exist in standard C.
strncat(resulta t,temporaire,lo ngueur+1);
strrev(resultat );

return resultat;
}
You also fail to define strncat via #include <string.h>. The
function name "strmid" is reserved for the implementation, i.e.
you may not use it or anything beginning with "str".

It doesn't work properly, but I really don't understand why.
Can anyone enlighten me? Or, if there's a similar code that
works already, can I have it please?


So let us design a substring extractor, say:

#include <stdlib.h> /* so we can use calloc */

char *substr(const char *s, size_t first, size_t length)
/* Notice the const, because from your usage example you plan to
use it on unalterable strings. The other parameters should be
size_t, because they can be any size available in the system, and
cannot be negative. */
{
char * result;
size_t i;

result = calloc(length+1 ); /* create space for result */
/* I used calloc to ensure the result is zero terminated, and
length+1 to ensure there is the extra space for that zero
termination */
i = 0;
while (length--) { /* make the copy */
result[i] = s[first + i];
++i;
}
return result;
} /* untested, and not optimum */

Undefined for length==0 and various other evils.

Since your prototype did not supply a place for the substring to
be placed, we have to allocate that space within substr. That
means that whatever calls substr must ultimately free the pointer
returned.

--
Chuck F (cb********@yah oo.com) (cb********@wor ldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net> USE worldnet address!

Nov 13 '05 #13
Paul Hsieh wrote:

In article <3F***********@ earthlink.net>, jo********@eart hlink.net says...
#define LEN 256

char *substr(char *string, int start, size_t count) {
static char str[LEN];
[...]
return str;
}


<sarcasm>
Which is real damn useful if you try to do the following:

char a = substr ("This is a string", 6, 4);
char b = substr (a, 2, 1);
printf ("<%s>, <%s>\n", a, b);

</sarcasm>

Ok, but assigning char* to char will stop you before anything else.
--
Joe Wright http://www.jw-wright.com
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Nov 13 '05 #14
qe*@pobox.com (Paul Hsieh) writes:
<sarcasm>
Which is real damn useful if you try to do the following:

char a = substr ("This is a string", 6, 4);
char b = substr (a, 2, 1);
printf ("<%s>, <%s>\n", a, b);

</sarcasm>

not worse than strtok ;-)

Happy C hacking
Friedrich
Nov 13 '05 #15
On 6 Dec 2003 14:58:59 GMT, in comp.lang.c , "A. Sinan Unur"
<as**@c-o-r-n-e-l-l.edu> wrote:
Mark McIntyre <ma**********@s pamcop.net> wrote in
news:ue******* *************** **********@4ax. com:
On 6 Dec 2003 06:37:36 GMT, in comp.lang.c , "A. Sinan Unur"
<as**@c-o-r-n-e-l-l.edu> wrote:
I guess 'depart' in French means something other than 'depart' in
English.


Not trying to be rude, but the meaning of his variable names is
utterly irrelevant.


But sir, it does make a difference to me in terms of comprehending an
undocumeted function.


Top tip: Never rely on the variable names as documentation, especially
in code you are not familiar with. It is absolutely guaranteed to bite
you in the a*se when you least need ir. And it will always totally
fsck you over when working with multilingual programmers....

--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.c om/ms3/bchambless0/welcome_to_clc. html>
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Nov 13 '05 #16
Although it was never completed, I think you'll find that the libclc
code on sourceforge has what you need, and a lot more that you may
not need.

:-)

http://sourceforge.net/projects/libclc/

--
Randy Howard _o
2reply remove FOOBAR \<,
_______________ _______()/ ()_____________ _______________ _______________ ___
SCO Spam-magnet: po********@sco. com
Nov 13 '05 #17
Groovy hepcat Olivier Bellemare was jivin' on Sat, 06 Dec 2003
03:25:58 GMT in comp.lang.c.
Getting the middle of a string's a cool scene! Dig it!
I've tried to make a function that returns the middle of a string. For
example:
strmid("this is a text",6,4); would return "is a".

Here is my code:
char *strmid(char *texte, int depart, int longueur)
Avoid function names beginning with "str". They are reserved
identifiers. (To be more precise, all identifiers with external
linkage beginning with "str" followed by a lower case letter are
reserved.)
{ char *resultat = " ";
char *temporaire = " ";
int nbr;

nbr = depart + longueur - 1;

strncat(tempora ire,texte,nbr);
Uh oh! You've just caused undefined behaviour. First of all,
temporaire points to a string literal, which may be in memory marked
read only. You are attempting to modify this string literal. This can
cause a crash. And secondly, even if you can modify the string literal
without problems, you have another problem. Your string literal is
only 2 bytes long (one byte for the space and one byte for the
terminating null character). But you are attempting to add more bytes
to the end of it. Result: you are writing into some random memory
location. This also produces undefined behaviour.
On top of that, your string literal contains a space, and you are
attempting to append a string to the end of this string literal. So,
even if the operation succeeded, you'd end up with a space at the
start of the resulting string, which isn't in the original string. I'm
sure this is not desired.
strrev(temporai re);
There's no such function in standard C, and I don't see a
declaration of this in your code, let alone a definition. (And it's a
reserved identifier anyhow. See above.)
strncat(resulta t,temporaire,lo ngueur+1);
And once again you are attempting to modify a string literal and
write beyond the end of it. But here you have yet another problem.
Both temporaire and resultat point at a string literal with the same
content. These two string literals are allowed to be folded into one.
In that case, you're writing a string to the end of itself. This is a
big problem.
But that's not all. strncat() doesn't always append a null character
to the end of the sequence, so it may not be a string. (Remember, a
string ends with a null character.)
strrev(resultat );
See above.
return resultat;
Note: if you return (the address of the first element of) an array
with automatic duration, you will have another problem. Automatic
variables no longer exist after the function returns. String literals
have static duration, however. But, as I've already shown, string
literals cause other problems.
}

It doesn't work properly, but I really don't understand why. Can anyone
enlighten me? Or, if there's a similar code that works already, can I have
it please?


Sure, here you go. I've included functions that get the rightmost
and leftmost parts of a string too, in case you need them at some time
in the future.

#include <assert.h>
#include <stdio.h>
#include <string.h>

/* copies 'len' characters from offset 'off' of string 'src' to 'dst'
returns dst */
char *substr(char *dst, const char *src, int off, int len)
{
assert(NULL != dst);
assert(NULL != src);
assert(0 <= len);
assert(0 <= off);

sprintf(dst, "%.*s", len, src + off);
return dst;
}

/* copies rightmost 'len' characters from 'src' to 'dst'
returns dst */
char *rightstr(char *dst, const char *src, int len)
{
const char *p;
int sl;

assert(NULL != dst);
assert(NULL != src);
assert(0 <= len);

if(len >= (sl = strlen(src)))
p = src;
else
p = src + sl - len;

sprintf(dst, "%.*s", len, p);
return dst;
}

/* copies leftmost 'len' characters from 'src' to 'dst'
returns dst */
char *leftstr(char *dst, const char *src, int len)
{
assert(NULL != dst);
assert(NULL != src);
assert(0 <= len);

sprintf(dst, "%.*s", len, src);
return dst;
}

--

Dig the even newer still, yet more improved, sig!

http://alphalink.com.au/~phaywood/
"Ain't I'm a dog?" - Ronny Self, Ain't I'm a Dog, written by G. Sherry & W. Walker.
I know it's not "technicall y correct" English; but since when was rock & roll "technicall y correct"?
Nov 14 '05 #18

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

Similar topics

5
1744
by: Penny | last post by:
Hi again, Thanks to those who helped before but I'm afraid I waisted your time and effort(especially Bob's) by not detailing the way I was trying to dynamically create the select statement. I thought if I showed you a simpler 'hard coded' version it would be easier to give pointers but all it did was remove the crucial elements. Here is what I'm attempting to do. ....................................................
5
2258
by: Yoshitha | last post by:
Hi I am working on a web project. I have a InstallerClass in my project. While making setup ( using web setup template) for this web application, I have added a userinterface with 4 textboxs, and added assembly to CustomActions-->Install
5
5537
by: David Requena | last post by:
Hi All, I'm trying to parse a file which has some timestamps embedded. These're expressed as a number of seconds elapsed since 01/01/1904 (macintosh time). I know OS X provides some APIs to handle these but fact is I'm not coding on a mac. Standard C functions that I've been looking at ( for example char *ctime(const time_t *time); ) take a time_t based on 01/01/1970.
2
1750
by: Gidi | last post by:
hello, i have a datagrid and i want to deal with the string that enter on a currentCell after each KeyPress and data entering, the problem is that while i'm still at the same cell i get that the string is "" till i'll move to the next cell and then i will get the string. how can i get the string after each keypress? thank you
4
1664
by: Mr. x | last post by:
Hello, I have declared in my program (*.aspx) something like this : <%@ Page Language="VB" Debug="true" %> .... <% dim current_view_page current_view_page = "1"
4
1583
by: PJ6 | last post by:
I can't find any built-in way to do this. I'm assigning an HTML cell a bgcolor and want to do it from a real color FromArgb... how do I get the # string to assign it to the HTML cell? Or do I have to code a translator up myself? TIA, Paul
9
3525
by: CapCity | last post by:
We're rewritting an app using C# 2005 and it needs to read files in netCDF format. A dll is available for this and we've had success in calling its functions, unless it updates strings. We have tried several of the suggestions we've found on-line: Strings, StringBuilders, IntPtr, etc., but haven't been able to exactly pull it off. What seem to be closest is the following. It's a function that will return a variable name for a given file...
0
1108
by: manicmax | last post by:
Hey I have a question for u I am taking connection string from IIS like this readonly string dataSource3 =ConfigurationManager.ConnectionStrings.ConnectionString; and using this dataSource3 variable above the page_load (to make this connection obj global) SqlConnection dbConn_data = new SqlConnection(dataSource3); But....
1
1230
by: mcmahon | last post by:
Hi, I keep getting the error " Object reference not set to an instance of an object." in relation to the line : selA = CType(lstStudents.Items(r.Index), String) Any advice/help? Dim BRow As DataRow Dim i As Integer Dim selA As String selA = CType(lstStudents.Items(r.Index), String) BRow = objDataSet.Tables("tblStudent").Rows.Find(selA)
1
3361
by: prasanna ganesh | last post by:
why i'm getting lang.string.NumberFormatException for input string ""please help me to find solution
0
9931
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
10725
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
10830
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
10403
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
7113
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
5781
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
5978
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4601
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4198
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.