简体   繁体   English

如何根据字符长度拆分字符串

[英]how to split string according to character length

I have a string which has say 3000 characters, now I want to split the same into array, where each index holding not more than 500 characters, I am not getting the logic for the same. 我有一个字符串,说有3000个字符,现在我想把它分成数组,每个索引保存不超过500个字符,我没有得到相同的逻辑。 I tried the below one but its not working.. 我尝试了下面的一个,但它没有工作..

say string arr holding 3000 characters... 说字符串arr持有3000个字符...

I am using a loop to get the characters length of 500 我正在使用循环来获得500的字符长度

here i am storing the value returned by the loop in an array... 这里我将循环返回的值存储在一个数组中......

say

ArrayList ar = new ArrayList();

for(int i=0; i < arr.Length; i+=500)
{
    ar.Add(arr.Substring(i,500));
}  

Response.Write(ar[0].ToString());

but this throws an error message saying 但这会抛出一条错误信息

Index and length must refer to a location within the string. 索引和长度必须指向字符串中的位置。

Please reply with the appropriate code for the same, any reply would be greatly appreciated. 请回复相应的相应代码,任何回复将不胜感激。

Couple of points: 几点:

you might need to test "i < arr.length - 1" as when you reach end the last index of the string is 2999 and the length is 3000. 您可能需要测试“i <arr.length - 1”,因为当您到达结束时,字符串的最后一个索引是2999,长度是3000。

You also might need to generalize the end point as you're assuming that the string is whole numbers of 500 long. 您也可能需要概括终点,因为您假设字符串是500长的整数。 If your string is 2900 long then the last string should be arr.Substring(i,400). 如果你的字符串是2900长,那么最后一个字符串应该是arr.Substring(i,400)。

Maybe try 也许试试吧

for(int i=0; i < arr.Length; i+=500)
{
    ar.Add(arr.Substring(i, Math.Min(arr.length - i,500)));
}  

The problem is that your arr-string isn't always 500 long. 问题是你的arr-string并不总是500长。 If you are getting to the end of it, it might only be 300 chars long. 如果你到了最后,它可能只有300个字符长。 Trying to substring 500 chars out of it will result in an out of range error. 尝试将500个字符串子串起来将导致超出范围的错误。

You should check the length of your arr when you substring it. 你应该检查arr的长度。 If it's shorter than your 500-charlength strings you should just take the whole string instead of trying to substring it further. 如果它比你的500-charlength字符串短,你应该只取整个字符串而不是尝试进一步子串。

Change to 改成

for(int i=0; i < arr.Length-1; i+=500)
{
    ar.Add(arr.Substring(i,500));
} 

Try changing to 尝试改为

for(int i=0; i < arr.Length; i+=500)
{
    int len=500;
    if(arr.Length<i+500)
    {
        len=arr.Length;
    }
    ar.Add(arr.Substring(i,len));
}

Try this... 尝试这个...

    static void Main(string[] args)
    {
        StringBuilder sb = new StringBuilder();
        string str = string.Empty;

        for (int i = 0; i < 3001; i++)
            sb.Append("a");

        str = sb.ToString();

        ArrayList arrayList = new ArrayList();
        int length = str.Length;
        int size = 500;
        int start = 0;

        while (length > 0)
        {
            if (length >= size)
                arrayList.Add(str.Substring(start, size));
            else
                arrayList.Add(str.Substring(start, length));

            start += size;
            length -= size;
        }

        Console.Write(arrayList[0].ToString());
    }
string str = "Sample Text";

        List<string> lst = new List<string>();
        while (str.Length > 500)
        {
            var temp = str.Substring(0, 500);
            str = str.Remove(0, temp.Length);
            lst.Add(temp);
        }

        lst.Add(str);

        string[] arrayString = lst.ToArray();
        Console.ReadLine();

In addition to the given answers, here is an alternative approach: 除了给出的答案,这里有一个替代方法:

List<string> ar = new List<string>();

int charcount = 500;
int index = 0;
do
{
    ar.Add(new string(input.Skip(index).Take(charcount).ToArray()));
    index += charcount;
} while (index < input.Length);

First, it uses List<string> instead of ArrayList ( ArrayList is not type-safe in the same manner and should basically not be used; it's still around mostly for backwards compatibility reasons). 首先,它使用List<string>而不是ArrayListArrayList以相同的方式不是类型安全的,基本上不应该使用;它仍然主要是出于向后兼容的原因)。

Second, since String implements IEnumerable<char> this opens up for using LINQ extensions. 其次,由于String实现了IEnumerable<char>因此可以使用LINQ扩展。 So I use Skip and Take to slice up the string into 500-character arrays that are turned into strings and added to the list. 所以我使用SkipTake将字符串切成500个字符的数组,这些数组转换成字符串并添加到列表中。

hey guys i have got an easy solution for the same, as said by "J. Vermeire", that the my string never has 500 characters in the end, it might be less than 300, thats why the application is throwing an error.. 嘿家伙我有一个简单的解决方案,如“J. Vermeire”所说,我的字符串最后从不有500个字符,它可能少于300,这就是应用程序抛出错误的原因..

so applying that logic i made a simple loop which could check whats the current length of the string and accordingly set the output.... here we go.. 所以应用这个逻辑我做了一个简单的循环,可以检查字符串的当前长度,并相应地设置输出....这里我们去..

here we assume string str contains 34905 characters. 这里我们假设string str包含34905个字符。

for(int i=0; i < str.Length; i += 500)
{
    if (str.Length > i+500)
    {
         Response.Write(str.Substring(i, 500));
    }
    else
    {
         Response.Write(str.Substring(i, str.Length-i));
    }

}

This has done my task.. Thanks "J. Vermeire" for giving your logic, its all your credit... Thanks a lot. 这已经完成了我的任务..感谢“J. Vermeire”给出了你的逻辑,它的所有功劳......非常感谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM