Click here to Skip to main content
15,943,061 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
say in a file, i have this text.

Go to Jail 10
Visit Virgina Avenue 19
Go to New York Avenue 31

is there a way that all strings in the text file will be saved in an string array
and all integers will be stored in an int array?
chandanadhikari 7-May-15 8:01am    
yes it can be done, try along these lines:
read the text file line by line
for each line you read into a string
in this string find if it contains digit.
Populate separate arrays of strings and digits accordingly.
Richard MacCutchan 7-May-15 8:13am    
Only if you write some code to do it.
Reuben Cabrera 7-May-15 8:27am    
do I need to convert the digit into an int or simply just store it in an int variable?
Reuben Cabrera 7-May-15 9:52am    
cant use the stoi function and atoi uses a const char * to be used. how can I use stoi. i did something but it didnt work.

1 solution

Nothing as standard will do that for you: you have to process them yourself, and that's possibly more complex that you think.

It's OK when your text is in exactly the form you show: string followed by a number on each line - but what if the string contains the number? Is that two strings and one number? Or the string up to the number, and ignore the rest? Or just ignore it all?

It's easy to get all the lines in the file as separate strings:
string[] lines = File.ReadAllLines(path);
Will do it, and it's easy to process each line into two parts assuming the number is at the end - a simple regex will do that:
All you have to do then is use int.Parse to convert the number match to an integer.

[edit]HTML tag autocompletion...[/edit]
Share this answer
Reuben Cabrera 7-May-15 8:47am    
i dont this part


how can i do that do you have a sample code?
OriginalGriff 7-May-15 8:53am    
It's a Regex, that's all.
Have you not met them yet?
Reuben Cabrera 7-May-15 9:42am    
unfortunately no :(
OriginalGriff 7-May-15 10:00am    
Have a look at MSDN: they are seriously powerful text processi=ors and really useful when you work with strings. They can look difficult to understand, but there are tools that help:
Is well worth a download!

For the moment, copy and paste this:

Regex reg = new Regex(@"(?<string>.*?)(?<number>\d+)$");
string line = "Go to New York Avenue 31";
Match m = reg.Match(line);
if (m.Success)
string text = m.Groups["string"].Value;
int number = int.Parse(m.Groups["number"].Value);

And give it a try in the debugger. You'll see what I mean.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900