1.

Solve : Replacing spaces with underscores in a string?

Answer»

I have a string which has spaces in it, and I NEED to replace all of the spaces with UNDERSCORES:

e.g.
This is my string -> This_is_my_string

No idea how to do this...

Thanks,
darrylThe easiest way is open the containing document in Wordpad and use the find/replace function.perhaps i should have elaborated... i need to do this within dos.. in a batch file...

sorry for the confusion,
darrylPerhaps you should have elaborated more! Where is this string coming from? A file? A LITERAL?

This will work for a literal, but with a little imagination, you should be able to get it to work from a file.

Code: [Select]@echo off
for /f "tokens=1-4" %%w in ("This is my string") do (
echo %%w_%%x_%%y_%%z
)

Good luck. 8-) Personally I like 2k_dummy's response...it cuts down on all those pesky tokens.If using W9x or real DOS, that won't work. It can still be done using Edit. Edit has a replace function.Quote

I have a string which has spaces in it, and I need to replace all of the spaces with underscores:

e.g.
This is my string -> This_is_my_string

No idea how to do this...

Thanks,
darryl


if you have PYTHON

Code: [Select]C:\>python -c "PRINT 'This is a string'.replace(' ','_') "
This_is_a_string

I do like the python solution, but once I get the return from the line:

C:\>python -c "print 'This is a string'.replace(' ','_') "
This_is_a_string

(i.e. the part that says "This_is_a_string"), how do I put that part into a new string?

Thanks,
darrylwell since you have Python, just do a Python script

Code: [Select]s = "This is my string"
result = s.replace(" ", "_") #store the result in variable
print result

save the code as test.py. Then from command prompt, type
c:\> python test.py




Discussion

No Comment Found