TIP: Click on subject to list as thread! ANSI
echo: c_echo
to: Simon Avery
from: George White
date: 1998-08-30 18:07:00
subject: Extraction of a substrin

Hi Simon,

You wrote to Jussi Hamalainen:

SA> JH> This is probably a stupid question, but...
SA> JH> I have a string and I need to extract a substring of length n,
SA> JH> starting at character number p. How do I do it?

SA>{
SA>int junk;
SA>char str1[100];
SA>char str2[20];

SA>// fill str1 with whatever.

SA>for (junk=p; junk!=100; junk++)
SA>        {
SA>        str2[junk-p]=str1[p];

SA>        if (str1[p]==0)     break;   // hit the terminating null

SA>        if ((junk=p) == n)   break;   // exceeding max_len n
SA>        }
SA>str2[junk-p]='\0';
SA>}

SA>That should do it,

I can't see quite what your code does, but it certainly doesn't "do it".

SA>                   but check the str* functs as well, ISTR there
SA>being something that'll do that.

strncpy()

Try:-

#include 
#include 

char *extract_string (char *dest,char *source,int start,int max_len)
{
char *str1,*str2;
int count = 0;

str1 = source + start;
str2 = dest;

while ((0 != (*str2++ = *str1++)) && (max_len > count++))
    ;

*str2 = 0;
return dest;
}

int main (void)
{
char test_string[] = "acdefghijkl";
char dest_string[20],second_string[20];
int  offset = 5,length = 10;

extract_string (dest_string,test,string,offset,length);
strncpy (second_string,&test_string[offset],length);

printf ("Input string '%s'\n",test_string);
printf ("Extracted string '%s'\n",dest_string);
printf ("strncpy() string '%s'\n",second_string);

return 0;
}

George

 * SLMR 2.1a * Computers eliminate spare time.

--- Maximus/2 3.01
* Origin: DoNoR/2,Woking UK (44-1483-717904) (2:440/4)
SEEN-BY: 396/1 622/419 632/0 371 633/260 267 270 371 634/397 635/506 728 810
SEEN-BY: 639/252 670/213 218
@PATH: 440/4 255/1 251/25 2320/38 270/101 396/1 633/260 635/506 728 633/267

SOURCE: echomail via fidonet.ozzmosis.com

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.