473,574 Members | 2,307 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Question about the split function

Hi, I am trying to parse a colon delimited text file.

Assume these as examples:

Book:mybook
Video:myvideo
Name:myname
When I use this:

ReadFromFile("c :\\Inetpub\\www root\\myfile.tx t");
}
public void ReadFromFile(st ring filename)
{
StreamReader SR;
string S;
string[] myStr;
SR=File.OpenTex t(filename);
S=SR.ReadLine() ;
while(S!=null)
{
myStr = S.Split(new char[] { ':' });
Response.Write( myStr[0] + "<BR>");
S=SR.ReadLine() ;
}
SR.Close();
}

On my web page I get this:

Book
Video

What I am trying to get is the stuff on the other side of the colon.
How can I get either the data on the other side of the colon or just
the entire line?

Thank you for any help.

Jan 26 '06 #1
9 2175
It is working correctly you are just printing out the first value only.

Split returns an array of strings (myStr[0], myStr[1], etc.) that each
contain a value.

So in your example:
myStr[0] = Book
myStr[1] = mybook

myStr[0] = Video
myStr[1] = myvideo

--
~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~
Charles Cox
VC/VB/C# Developer
~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~

<ne***********@ gmail.com> wrote in message
news:11******** *************@g 44g2000cwa.goog legroups.com...
Hi, I am trying to parse a colon delimited text file.

Assume these as examples:

Book:mybook
Video:myvideo
Name:myname
When I use this:

ReadFromFile("c :\\Inetpub\\www root\\myfile.tx t");
}
public void ReadFromFile(st ring filename)
{
StreamReader SR;
string S;
string[] myStr;
SR=File.OpenTex t(filename);
S=SR.ReadLine() ;
while(S!=null)
{
myStr = S.Split(new char[] { ':' });
Response.Write( myStr[0] + "<BR>");
S=SR.ReadLine() ;
}
SR.Close();
}

On my web page I get this:

Book
Video

What I am trying to get is the stuff on the other side of the colon.
How can I get either the data on the other side of the colon or just
the entire line?

Thank you for any help.

Jan 26 '06 #2
Let me fix your code...
First of all if you are trying to parse a file which is less than 10 MB u
may use File.OpenText otherwise u should use StreamReader

public void ReadFromFile(st ring pFilename)
{
StreamReader sr = null;
String sLine;
String[] stringData;
try
{
sr = File.OpenText(p Filename);
while (sr.Peek()>=0)
{
sLine= sr.ReadLine();
stringData= sLine.Split(':' ); // Only available with 2.0
if (stringData.Len gth > 1)
Console.WriteLi ne("{0}\t{1}",s tringData);
}
}
finally
{
if (sr != null)
sr.Close();
}
}

Also, u can access "mybook" using stringData[1]
--
HTH

Thanks,
Yunus Emre ALPÖZEN
BSc, MCSD.NET
Microsoft .NET & Security MVP

<ne***********@ gmail.com> wrote in message
news:11******** *************@g 44g2000cwa.goog legroups.com...
Hi, I am trying to parse a colon delimited text file.

Assume these as examples:

Book:mybook
Video:myvideo
Name:myname
When I use this:

ReadFromFile("c :\\Inetpub\\www root\\myfile.tx t");
}
public void ReadFromFile(st ring filename)
{
StreamReader SR;
string S;
string[] myStr;
SR=File.OpenTex t(filename);
S=SR.ReadLine() ;
while(S!=null)
{
myStr = S.Split(new char[] { ':' });
Response.Write( myStr[0] + "<BR>");
S=SR.ReadLine() ;
}
SR.Close();
}

On my web page I get this:

Book
Video

What I am trying to get is the stuff on the other side of the colon.
How can I get either the data on the other side of the colon or just
the entire line?

Thank you for any help.

Jan 26 '06 #3
Thanks! Do you know if there is a way to start back over at the
beginning of the file? Sometimes there are error codes in a given text
file. I only want to parse the ones that have errors. So I thought
that if I searched once for "ERROR:" and if it had it I could go back
to the top of the file and start actually getting data. I thought this
might be better than getting data only to find out that I really don't
need to have captured from it in the first place. Doesn't sound like
much, but there could be a thousand text files to search through.

Jan 26 '06 #4
> Let me fix your code...

;)
stringData= sLine.Split(':' ); // Only available with 2.0


What are you talking about? String.Split(ch ar) has been with us for a long
time now. ;)

Anyway...I like mine better :)

using (StreamReader reader = File.OpenText(" myfile.txt"))
{
while(reader.Pe ek() != -1)
{
string line = reader.ReadLine ();

string[] parts = line.Split(':') ;

Console.WriteLi ne("{0} : {1}", parts[0], parts[1]);
}
}

Chris
Jan 26 '06 #5
If you only want to process lines that contain the string "ERROR:" before
the delimiter, you have no need to go through the file twice.

Simply test for the presence of "ERROR:" in myStr[0] (example):

sLine= sr.ReadLine();
stringData= sLine.Split(':' );
if(stringData[0]=="ERROR")
{

// your cool processing code here
}

-- That's all.
Peter
--
Co-founder, Eggheadcafe.com developer portal:
http://www.eggheadcafe.com
UnBlog:
http://petesbloggerama.blogspot.com


"ne***********@ gmail.com" wrote:
Thanks! Do you know if there is a way to start back over at the
beginning of the file? Sometimes there are error codes in a given text
file. I only want to parse the ones that have errors. So I thought
that if I searched once for "ERROR:" and if it had it I could go back
to the top of the file and start actually getting data. I thought this
might be better than getting data only to find out that I really don't
need to have captured from it in the first place. Doesn't sound like
much, but there could be a thousand text files to search through.

Jan 26 '06 #6
As you are creating a file stream you should be able to Seek to the
beginning.
A definition of SR like:

public void ReadFromFile(st ring filename) {
StreamReader SR;
string S;
string[] myStr;
FileStream fs = new FileStream(file name,FileMode.O pen);
SR= new StreamReader(fs );
S=SR.ReadLine() ;
while(S!=null) {
myStr = S.Split(new char[] { ':' });
Response.Write( myStr[0] + "<BR>");
S=SR.ReadLine() ;
}
SR.Close();
}

You would get a FileStream to file called fs.
You could then use :
fs.Seek(0,SeekO rigin.Begin);

To jump back to the beginning of the file.

HTH

Ciaran
<ne***********@ gmail.com> wrote in message
news:11******** **************@ z14g2000cwz.goo glegroups.com.. .
Thanks! Do you know if there is a way to start back over at the
beginning of the file? Sometimes there are error codes in a given text
file. I only want to parse the ones that have errors. So I thought
that if I searched once for "ERROR:" and if it had it I could go back
to the top of the file and start actually getting data. I thought this
might be better than getting data only to find out that I really don't
need to have captured from it in the first place. Doesn't sound like
much, but there could be a thousand text files to search through.

Jan 26 '06 #7
Ciaran <ci****@theodon nells.plus.com> wrote:
As you are creating a file stream you should be able to Seek to the
beginning.
<snip>
You would get a FileStream to file called fs.
You could then use :
fs.Seek(0,SeekO rigin.Begin);

To jump back to the beginning of the file.


Just to mention that a somewhat more readable (IMO) way of doing a Seek
is to use the Position property:

fs.Position = 0;

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jan 26 '06 #8
Hi Chris,
I really like your joke. The overload i had used with my code available
since 2.0. Original one was

"stringData = sLine.Split(new char[] { ':' },
StringSplitOpti ons.RemoveEmpty Entries);"
But then update my code for clarity. Thanks for your notice..

Anyway, using "using" keyword is same as using "try_finall y" blocks. I used
to implement my codes using four languages (C#, VB.NET, J#, C++.NET) as
writing articles, writing posts.. And unfortunately using is not available
for J# and C++.NET yet :( Also it is available for VB.NET since 2.0... So I
prefer using "try_finall y" blocks force of habit :)

--
HTH

Thanks,
Yunus Emre ALPÖZEN
BSc, MCSD.NET
Microsoft .NET & Security MVP

"chris martin" <chris_m|NOSPAM |@caliber|SPAM| web.com> wrote in message
news:44******** *************** ***@news.easyne ws.com...
Let me fix your code...


;)
stringData= sLine.Split(':' ); // Only available with 2.0


What are you talking about? String.Split(ch ar) has been with us for a long
time now. ;)

Anyway...I like mine better :)

using (StreamReader reader = File.OpenText(" myfile.txt"))
{
while(reader.Pe ek() != -1)
{
string line = reader.ReadLine ();

string[] parts = line.Split(':') ;

Console.WriteLi ne("{0} : {1}", parts[0], parts[1]);
}
}

Chris

Jan 27 '06 #9
<"Yunus Emre ALPÖZEN [MVP]" <yemre>> wrote:

<snip>
Anyway, using "using" keyword is same as using "try_finall y" blocks. I used
to implement my codes using four languages (C#, VB.NET, J#, C++.NET) as
writing articles, writing posts.. And unfortunately using is not available
for J# and C++.NET yet :( Also it is available for VB.NET since 2.0... SoI
prefer using "try_finall y" blocks force of habit :)


Even if you're writing articles or posts though, I'd use idiomatic
language where possible - and the preferred idiom for disposing of
objects in C# *is* to use the using statement. Might as well use it in
languages where it's available...

(I would personally not use Peek, by the way - keep reading lines until
reader.ReadLine returns null.)

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jan 27 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
415
by: alexk | last post by:
I've a simple question. Why the following: words = "123#@$#$@^% wordB#@$".split('~`!@#$%^&*()_+-={},./') doesn't work? The length of the result vector is 1. I'm using ActivePython 2.4 Alex
11
2077
by: Joseph Turian | last post by:
Fellow hackers, I have a class BuildNode that inherits from class Node. Similarly, I have a class BuildTree that inherits from class Tree. Tree includes a member variable: vector<Node> nodes; // For clarity, let this be "orig_nodes" BuildTree includes a member variable:
6
6365
by: Senthil | last post by:
Code ---------------------- string Line = "\"A\",\"B\",\"C\",\"D\""; string Line2 = Line.Replace("\",\"","\"\",\"\""); string CSVColumns = Line2.Split("\",\"".ToCharArray());
19
4668
by: morc | last post by:
hey, I have float values that look something like this when they are printed: 6.0E-4 7.0E-4 I don't want them to be like this I want them to be normalized with 4 decimal places.
13
1713
by: Eric_Dexter | last post by:
All I am after realy is to change this reline = re.line.split('instr', '/d$') into something that grabs any line with instr in it take all the numbers and then grab any comment that may or may not be at the end of the line starting with ; until the end of the line including white spaces.. this is a corrected version from ...
4
3283
by: Peter Proost | last post by:
Hi group, it's been a long time since the last time I've been here but I have a question. I'm working with timespan.parse for calculating a duration, I have to add strings which are in the following format 15:36:12 ==Hours, minutes, seconds but sometimes there is a string like 55:26:32 ==which is correct cause the production machine was...
6
1465
by: zhengyan11 | last post by:
my job is to check the cookie and then decide if I show a image link on the page when the page is loaded. this is what I did: <html> <head> <TITLE>THIS IS TEST </TITLE>
1
2423
by: John | last post by:
Hi I have written a Split function which in turn calls the standard string split function. Code is below; Function Split1(ByVal Expression As String, Optional ByVal Delimiter As String = " ", Optional ByVal Limit As Integer = -1, Optional ByVal Compare As CompareMethod = CompareMethod.Binary, Optional ByVal MaxLength As Integer = 0) As...
25
5382
by: bonneylake | last post by:
Hey Everyone, Well i am not sure if my question needs to be here or in coldfusion. If i have my question is in the wrong section i am sorry in advance an will move it to the correct section. Basically i have a multiple select box. An it works except for this one part i want to add to it.The first box i have is called project members which...
2
2626
by: gdarian216 | last post by:
I am writting a program that has three different files and is compiled by a Makefile. The goal is to take a file of text and split it up in different sections and stored in vectors. Then it outputs the information in a standard format. The main is fine and my function declarations are good also I am just having trouble writing the functions. Below...
0
7831
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
8092
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8262
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
8129
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6497
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5641
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5331
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3785
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1364
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.