Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

replacing xth character on each line in text file

Status
Not open for further replies.

saadabc

Programmer
Aug 5, 2004
107
US
I want to open a text file using VB .NET and replace the 20th character on each line with 0.

how can i do this?
 
I'm presuming that the reason for the question is how do you replace a character in a string at a certain position and that you are ok with file io.

You will need to read from one file and write to another (and after you have finished then delete the original file and rename the new file if necessary)

As you read in each line then assuming the initial value of the line is in s and you want to replace the character at position 20 with A then:

Dim s As String = "123456789012345678901234567890"
MessageBox.Show(s)
s = s.Remove(19, 1).Insert(19, "A")
MessageBox.Show(s)

so reading a file you woulkd use s = sr.ReadLine and after processing sw.WriteLine(s)


Hope this helps.

[vampire][bat]
 
On reflection, a better solution might be:

If s.Length > 19 Then
s = s.Remove(19, 1).Insert(19, "A")
MessageBox.Show(s)
Else
MessageBox.Show(s + " is too short")
End If

unless you know that every line will be at least 20 characters long.


Hope this helps.

[vampire][bat]
 
Doesn't String have a .Char(index) method? I'll have to double check tomorrow, but I would think

Code:
'open file
'while peeking is okay
'read line into [b]s[/b]
s.chars(20) = "0"
'write line [b]s[/b] into new file
'end loop
'copy new file over original

Ecuse my commented psuedo code, I don't have the file open/read/write code in front of me. I think there may be a FAQ on it though.

-Rick

VB.Net Forum forum796 forum855 ASP.NET Forum
[monkey]I believe in killer coding ninja monkeys.[monkey]
 
i got it.

used

Dim instr as streamreader
Dim infile as file

instr = infile.readtext("c:\infile.txt")

Dim ostr as streamwriter
Dim outfile as file
ostr = outfile.createtext("c:\outfile.txt")
Dim line as string = ""

while ostr.peek <> -1
line = instr.readline

..... 'code to replace characters in the string


ostr.writeline

end while


instr.close
ostr.close


sorry - it was a rather simple solution - but i needed it in a hurry - and i couldn't remember the file I/O code - hence i posted.


Thanks both of you ....

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top