读取TXT文件后,将内容存入到数组中,换行符被当作0存入,怎么去掉?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Collections;
using System.IO;
namespace ccs_getchar
{
class Program
{
static void Main(string[] args)
{
for (int n = 0; n < 6; n++)
{
Console.WriteLine();
Console.WriteLine("please input the chinese character:");
string chinese = Console.ReadLine();
string path = @"c:\asd\gbcdbig.txt";
string[] strNew;
int cctarget = 0;
ArrayList cc = new ArrayList();
string[] contents = File.ReadAllLines(path, Encoding.Default);
string flag = Convert.ToString('*');
for (int i = 0; i < contents.Length; i++)
{
strNew = contents[i].Split(new char[1] { ' ' }); //strNew.Indexof
// Console.WriteLine(contents[i]);
for (int m = 0; m < strNew.Length; m++)
{
if (strNew[m] == chinese)
{
if (cctarget == 0)
{
for (int j = 0; j < strNew.Length; j++)
{
cc.Add(strNew[j]);
}
cctarget = cctarget + 1;
break;
}
}
else if (cctarget == 1)
{
if (strNew[m] != flag)
{
for (int j = 0; j < strNew.Length; j++)
{
cc.Add(strNew[j]);
}
}
else
cctarget = cctarget + 1;
break;
}
else if (cctarget == 2)
break;
}
}
cc.RemoveRange(0, 4);
string[] rd_pos = (string[])cc.ToArray(typeof(string));
int[] pos_int = new int[rd_pos.Length];
for (int i = 0; i < rd_pos.Length; i++)
{
int.TryParse(rd_pos[i], out pos_int[i]);
}
foreach (var item in pos_int)
{
Console.Write(item + " ");
}
Console.ReadKey();
}
}
}
}
TXT的文件格式如下
ReadAllLines不会读取换行的,而且注意你的存储编码如果是utf-8的,ReadAllLines要制传递utf-8,要不会乱码
而且你的数组指的那个
换用 字节流 去读, 字符流读的结果不对
void main()
{
// string str;
char ch[200];
ifstream out("d:\data.txt",ios::in);
while(!out.eof())
{
//getline(out,str);
out.getline(ch,200,'\n');
cout<<ch<<endl;
}
out.close();
}
代码应该没问题,可能是数据文件有问题。比如最后有多个空格结尾,每多一个空格会转出来多一个0
可以考虑
strNew = contents[i].Split(new char[1] { ' ' });
改成
strNew = contents[i].Trim().Split(new char[1] { ' ' });
这个用vb6很好处理,用split函数,分解符就是换行符,分行前,用trim函数,去掉头尾空字符