C#의 특정 문자가 포함 된 파일로 읽기
-
20-09-2019 - |
문제
이름이 지정된 텍스트 파일이 있습니다 C:/test.txt
:
1 2 3 4 5 6
이 파일의 모든 번호를 사용하여 읽고 싶습니다. StreamReader
.
어떻게 할 수 있습니까?
해결책
정말로 사용해야합니까? StreamReader
이것을하기 위해?
IEnumerable<int> numbers =
Regex.Split(File.ReadAllText(@"c:\test.txt"), @"\D+").Select(int.Parse);
(한 번의 히트로 전체 파일을 읽는 것이 비현실적이라면 스트리밍해야하지만 사용할 수있는 경우 File.ReadAllText
그렇다면 그것이 제 생각에 그렇게하는 방법입니다.)
완전성을 위해 스트리밍 버전은 다음과 같습니다.
public IEnumerable<int> GetNumbers(string fileName)
{
using (StreamReader sr = File.OpenText(fileName))
{
string line;
while ((line = sr.ReadLine()) != null)
{
foreach (string item in Regex.Split(line, @"\D+"))
{
yield return int.Parse(item);
}
}
}
}
다른 팁
using (StreamReader reader = new StreamReader(stream))
{
string contents = reader.ReadToEnd();
Regex r = new Regex("[0-9]");
Match m = r.Match(contents );
while (m.Success)
{
int number = Convert.ToInt32(match.Value);
// do something with the number
m = m.NextMatch();
}
}
파일에서 정수를 읽고 목록에 저장하려면 원하는 것이 트릭을 수행 할 수 있습니다.
try
{
StreamReader sr = new StreamReader("C:/test.txt"))
List<int> theIntegers = new List<int>();
while (sr.Peek() >= 0)
theIntegers.Add(sr.Read());
sr.Close();
}
catch (Exception e)
{
//Do something clever to deal with the exception here
}
큰 파일에 대한 솔루션 :
class Program
{
const int ReadBufferSize = 4096;
static void Main(string[] args)
{
var result = new List<int>();
using (var reader = new StreamReader(@"c:\test.txt"))
{
var readBuffer = new char[ReadBufferSize];
var buffer = new StringBuilder();
while ((reader.Read(readBuffer, 0, readBuffer.Length)) > 0)
{
foreach (char c in readBuffer)
{
if (!char.IsDigit(c))
{
// we found non digit character
int newInt;
if (int.TryParse(buffer.ToString(), out newInt))
{
result.Add(newInt);
}
buffer.Remove(0, buffer.Length);
}
else
{
buffer.Append(c);
}
}
}
// check buffer
if (buffer.Length > 0)
{
int newInt;
if (int.TryParse(buffer.ToString(), out newInt))
{
result.Add(newInt);
}
}
}
result.ForEach(Console.WriteLine);
Console.ReadKey();
}
}
나는 틀렸을 수도 있지만 streamReader를 사용하면 구하고를 설정할 수 없습니다. 그러나 string.split ()를 사용하여 구하고 (케이스의 공간입니까?)를 설정하고 모든 숫자를 별도의 배열로 추출 할 수 있습니다.
이와 같은 것이 작동해야합니다.
using (var sr = new StreamReader("C:/test.txt"))
{
var s = sr.ReadToEnd();
var numbers = (from x in s.Split('\n')
from y in x.Split(' ')
select int.Parse(y));
}
이 같은:
using System;
using System.IO;
class Test
{
public static void Main()
{
string path = @"C:\Test.txt";
try
{
if( File.Exists( path ) )
{
using( StreamReader sr = new StreamReader( path ) )
{
while( sr.Peek() >= 0 )
{
char c = ( char )sr.Read();
if( Char.IsNumber( c ) )
Console.Write( c );
}
}
}
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
}
}
제휴하지 않습니다 StackOverflow