请教截取文本文件中包含汉字的长度

psyke99 2006-10-14 09:48:05
如何解决显示出来文本的不整齐
次 0000010.000001.000000000010.
次 0000010.000001.000000000010.0
次 0000005.000001.000000000005.
sr.ReadLine().Substring(52,44)如果有汉字这里没法控制


代码:
private void button1_Click(object sender, System.EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog ();
ofd.Filter="文本文件 (*.txt)|*.txt";
if(ofd.ShowDialog() == DialogResult.OK)
{
this.textBox1.Text = ofd.FileName.ToString();
}

StreamReader sr = new StreamReader(ofd.FileName,System.Text.Encoding.GetEncoding("GB2312"));
sr.BaseStream.Seek(0,SeekOrigin.Begin);
string line=sr.ReadLine() ;
while(sr.ReadLine() != null)
{

richTextBox1.Text +=sr.ReadLine().Substring(52,44)+"\n";
}
sr.Close();
}
...全文
232 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
Knight94 2006-10-17
  • 打赏
  • 举报
回复
to 但还是想不出一个思路如何取sr.ReadLine().Substring(52,44)之间的文本

你首先需要确定52与44是字符长度,还是字节长度,如果这个无法确定的话,是无法处理的。
psyke99 2006-10-17
  • 打赏
  • 举报
回复
解决了,用这方法就行啦.谢谢愚翁指点确定字节长度就可以了.

private void button2_Click(object sender, System.EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog ();
ofd.Filter="文本文件 (*E.txt)|*E.txt";
byte [] bwrite;//byte内容

if(ofd.ShowDialog() == DialogResult.OK)
{
this.textBox1.Text="";
StreamReader sr = new StreamReader(ofd.FileName,System.Text.Encoding.GetEncoding("GB2312"));
bwrite = Encoding.GetEncoding("GB2312").GetBytes(sr.ReadLine().ToCharArray());


this.textBox2.Text = bwrite.Length.ToString();
this.textBox1.Text = Encoding.Default.GetString(bwrite,52,44);
sr.Close();
}
psyke99 2006-10-16
  • 打赏
  • 举报
回复
打错修正
用这个就可以但取出之前的文本this.richTextBox1.Text +=getCountStr(sr.ReadLine(),52)+"\n";
但还是想不出一个思路如何取sr.ReadLine().Substring(52,44)之间的文本;
psyke99 2006-10-16
  • 打赏
  • 举报
回复
能计算中文的长度了,但出现全角符号还是不行.
旧帖中搜到此方法可以精确取出长度文本,
private string getCountStr(string str,int count)
{
byte [] bwrite=Encoding.GetEncoding("GB2312").GetBytes(str.ToCharArray());
if(bwrite.Length>=count)
return Encoding.Default.GetString( bwrite,0,count);
else return Encoding.Default.GetString(bwrite);
}

用这个就可以但取出之间的this.richTextBox1.Text +=getCountStr(sr.ReadLine(),52)+"\n";
还是想不出一个思路如何取sr.ReadLine().Substring(52,44)之间的文本;
Knight94 2006-10-15
  • 打赏
  • 举报
回复
用Encoding来判断字符长度,例如:
private int GetChsCharLength( string strValue )
{
if( strValue == null || strValue == "" ) return 0;

Encoding encGB = Encoding.GetEncoding( "gb2312" );
Encoding encUnicode = Encoding.Unicode;

return strValue.Length - ( encUnicode.GetByteCount( strValue ) - encGB.GetByteCount( strValue ) );
}

private int GetAniCharLength( string strValue )
{
if( strValue == null || strValue == "" ) return 0;

Encoding encGB = Encoding.GetEncoding( "gb2312" );
Encoding encUnicode = Encoding.Unicode;

return encUnicode.GetByteCount( strValue ) - encGB.GetByteCount( strValue );
}

110,545

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧