String split question

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
dthvwhvw
Posts: 2
Joined: 15 Oct 2021 12:21

String split question

#1 Post by dthvwhvw » 15 Oct 2021 12:28

Hi,
I just want to split a string like:

"1.no data 2.digital input 3.digital output"

into:

1.no data
2.digital input
3.digital output

I spent many hours using the 'for' command trying to do so but failed.

Hope you guys can help me out.

Aacini
Expert
Posts: 1730
Joined: 06 Dec 2011 22:15
Location: México City, México

Re: String split question

#2 Post by Aacini » 15 Oct 2021 13:08

How do you identify the end of each part? It can not be a space, because the data have spaces. You may use the point and then rearrange the results a little.

There are several ways to do such a process. I prefer this one:

Code: Select all

@echo off
setlocal EnableDelayedExpansion

set "string=1.no data 2.digital input 3.digital output"
echo %string%
echo/

set "p=%%"
set "i=0" & set "part[!i!]=%string:.=" & call set "part[!i!]=!p!part[!i!]:~0,-2!p!" & set /A "i+=1" & set "part[!i!]=%"

set part[
Output:

Code: Select all

1.no data 2.digital input 3.digital output

part[1]=no data
part[2]=digital input
part[3]=digital output
A detailed explanation on the method used is given at split string into substrings based on delimiter thread...

EDIT: I like this modification:

Code: Select all

@echo off
setlocal EnableDelayedExpansion

set "string=1.no data 2.digital input 3.digital output 6.analog input 9.analog output"
echo %string%
echo/

set "p=%%" & set "part="
set "i=%string:.=" & (if defined part call set "part[!i!]=!p!part:~0,-2!p!" & call set "i=!p!part:~-1!p!") & set "part=%" & set "part[!i!]=!part!"

set part[
Output:

Code: Select all

1.no data 2.digital input 3.digital output 6.analog input 9.analog output

part[1]=no data
part[2]=digital input
part[3]=digital output
part[6]=analog input
part[9]=analog output
Antonio

dthvwhvw
Posts: 2
Joined: 15 Oct 2021 12:21

Re: String split question

#3 Post by dthvwhvw » 16 Oct 2021 01:15

It's like magic...

I'll need some time to understand what you did but this works.

Thanks!

Post Reply