如何根据文本大小拆分文本文件 [英] how to split a text file basis on its size

查看:97
本文介绍了如何根据文本大小拆分文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须在用户定义的字符串中划分一个文本文件.....如果用户要求将文本文件分成10个部分,那么每个分割的字符串应该具有相同的大小(字节)......我有b $ b

在c#中使用了substring方法,但它不能满足我的需求而且我正在使用c#



给我任何建议或任何可能的解决方案....................................... ..



我必须使用c#才能这样做



....... .................................................. .......感谢

i have to divide a text file in user define strings ..... and if the user ask to divide the text file in 10 parts then every divided string should be of same size (bytes) ......i have

used the substring method in c# but it doesn't fulfill my needs and i am using c#

give me any suggestion or any possible solution .........................................

and i have to do this using c# only

................................................................thanks

推荐答案

使用此方法:



use this method:

static IEnumerable<string> SplitText(string str, int chunkSize)
{
  if (str.Length < chunkSize)
   {
     return new string[]{str};
   }
   return Enumerable.Range(0, str.Length / chunkSize)
         .Select(i =>
                   ((i * chunkSize) + chunkSize) <= str.Length ?
                   str.Substring(i * chunkSize, chunkSize):
                   str.Substring((i*chunkSize), str.Length-(i*chunkSize))
               );
}



使用它如:


use it like:

string mytext = "Quick brown fox jumps over the lazy dog!123456789";
string[] chunks = SplitText(mytext, 4).ToArray();





HTH!



HTH !


这里是一个非常简单的一步一步解决方案的概述:
Here's an outline of a very plain one step-at-a-time solution:
List<string> chunks = new List<string>();

string mytext = "Quick brown fox jumps over the lazy dog yet we!";

int sLen = mytext.Length;

int chunkSize = 4;

int remainder = sLen % chunkSize;

string pad = "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~";

for (int i = 0; i < sLen; i += chunkSize)
{
    if(i + chunkSize <= sLen)
    {
        chunks.Add(mytext.Substring(i, chunkSize));
    }
    else
    {
        chunks.Add(mytext.Substring(i, remainder) + pad.Substring(0, chunkSize - remainder));
    }
}

在此解决方案中,数据字符串的长度不能被块大小整除的情况通过填充最后一个元素中的余数字符来处理在列表中使用波形符(〜)。

In this solution the case that the length of the data string is not evenly divisible by the chunk size is handled by padding the "remainder" characters in the last element in the List with tilde characters (~).


试试这个..



Try this..

int size = 5;

double each = (double) mytext.Length / (double)size;
List<string> lstOut = new List<string> ();
for (int i = 0; i < size; i++)
    lstOut.Add(mytext.Substring(i * (int)each ,(int)each));


这篇关于如何根据文本大小拆分文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆