public
static
void
Main(
string
[] args)
{
a =
"abcd-efg,hi///jk|lmnop"
;
b =
" hello interop"
List<
> tokens =
new
>();
// get first token of string a using "-" as the delimiter
tokens.Add(Utility.StrTok(a,
"-"
));
// get next tokens of string a by setting the first argument to null
// each StrTok call can use a different delimiter
tokens.Add(Utility.StrTok(
null
,
","
"/"
// start tokenizing string b without finishing string a
tokens.Add(Utility.StrTok(b,
" "
foreach
(
token
in
tokens) {
Console.WriteLine(
"<{0}>"
, token);
}
<abcd>
<efg>
<hi>
<hello>
<interop>
<>
class
Utility
[DllImport(
"msvcrt.dll"
, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
extern
IntPtr strtok(IntPtr str,
delim);
IntPtr strtokBuffer = IntPtr.Zero;
StrTok(
str,
delim)
// if str is null
// continue tokenizing the same unmanaged string from previous strtok call
// if str is not null
// strtok will start tokenizing a new unmanaged string initialized with str
// if the token returned from strtok is IntPtr.Zero
// strtok has finished tokenizing the unmanaged string
IntPtr token;
if
(str ==
) {
token = strtok(IntPtr.Zero, delim);
else
IntPtr strAnsi = Marshal.StringToHGlobalAnsi(str);
token = strtok(strAnsi, delim);
Marshal.FreeHGlobal(strtokBuffer);
strtokBuffer = strAnsi;
(token == IntPtr.Zero) {
strtokBuffer = IntPtr.Zero;
return
Marshal.PtrToStringAnsi(token);
Utility : IDisposable
Dispose()
)
(token == IntPtr.Zero)
stringA =
stringB =
using
(var util =
Utility())
tokens.Add(util.StrTok(stringA,
tokens.Add(util.StrTok(
tokens.Add(util.StrTok(stringB,
//tokens.Add(StrTok(null, " "));
tokens)