Extracting smaller strings from a larger string

New to FreeBASIC? Post your questions here.
Post Reply
SMC
Posts: 33
Joined: Feb 22, 2012 4:05

Extracting smaller strings from a larger string

Post by SMC »

I'm getting weird results from something really simple. Maybe I'm doing something wrong. Simple logic sometimes confounds me. Anyway, I'm trying to extract small strings from a larger string using "_" as a separating character.

Code: Select all

Dim as String mr_str = "Hello_world_this_is_a_string"
Dim as String str_cont = ""

Dim as UInteger char_pos, start_pos = 1

Do
    ''get the information for the section of string
    char_pos = Instr(start_pos, mr_str, "_")
    print char_pos	''just left this in as a sanity check

    ''extract the string and print it to the screen
    str_cont = Mid(mr_str, start_pos, char_pos - 1)
    Print str_cont

    ''set a new start position
    start_pos = char_pos + 1

Loop While char_pos <> 0

End

Here are the results I'm getting:
6
Hello
12
world_this_
17
this_is_a_string
20
is_a_string
22
a_string
0
string


Any idea why I'm not getting single words back, or why my count is off?
fxm
Moderator
Posts: 12576
Joined: Apr 22, 2009 12:46
Location: Paris suburbs, FRANCE

Re: Extracting smaller strings from a larger string

Post by fxm »

I just corrected the one line (#12) in error:
str_cont = Mid(mr_str, start_pos, char_pos - start_pos)
D.J.Peters
Posts: 8641
Joined: May 28, 2005 3:28
Contact:

Re: Extracting smaller strings from a larger string

Post by D.J.Peters »

The strtok() function splits a string into multiple pieces (referred to as "tokens") using delimiters.

Syntax: strtok(char * str, const char * delimiters);

Joshy

Code: Select all

#include "crt.bi"

var aString  = "Hello_world_this_is_a_string"

dim as string splits(any)
var p = strtok(strptr(aString),strptr("_"))
while (p)
  redim preserve splits(ubound(splits)+1)
  splits(ubound(splits)) = *p
  p = strtok(NULL,strptr("_"))
wend
for i as integer=0 to ubound(splits)
  print i & " " & splits(i)
next  
sleep
SMC
Posts: 33
Joined: Feb 22, 2012 4:05

Re: Extracting smaller strings from a larger string

Post by SMC »

fxm wrote: Apr 05, 2025 18:21 I just corrected the one line (#12) in error:
str_cont = Mid(mr_str, start_pos, char_pos - start_pos)
I'm a doofus. I thought Mid() needed an end position. Thanks to both of you.
Post Reply