将字符串切割成每个<“x”字符的数组

时间:2013-10-24 18:49:05

标签: c# .net string

我的情况是我的字符串不能超过某一点,所以我想要做的是将其剪切成较小的“x”字符串,然后将它们一个接一个地打印在一起。它们并不都需要相等,如果x是5,并且我有一个11个字符的字符串,打印3行5,5和1个字符就可以了。在C#中有一种简单的方法吗?

示例:

string Test = "This is a test string";
stringarray = Cutup(Test, 5); 
//Result:
//"This "
//"is a "
//"test "
//"strin"
//"g"

10 个答案:

答案 0 :(得分:2)

尝试这样的事情:

    public string[] Cutcup(string s, int l)
    {
        List<string> result = new List<string>();

        for (int i = 0; i < s.Length; i += l)
        {
            result.Add(s.Substring(i, Math.Min(5, s.Substring(i).Length)));
        }

        return result.ToArray();
    }

答案 1 :(得分:0)

你可以剪掉字符串然后做一个test.lastIndexOf('');如果这有帮助

答案 2 :(得分:0)

您可以使用String Manipulation函数 Substring()和for循环来完成此任务。

答案 3 :(得分:0)

这是一个例子

int maxChars = 5;
            String myStr = "This is some text used in testing this method of splitting a string and just a few more chars and the string is complete";
            List<String> mySubStrings = new List<String>();
            while (myStr.Length > maxChars)
            {
                mySubStrings.Add(myStr.Substring(0,maxChars));
                myStr = myStr.Substring(maxChars);
            }
            mySubStrings.ToArray();

答案 4 :(得分:0)

        List<string> result = new List<string>();
        string testString = "This is a test string";
        string chunkBuilder = "";
        int chunkSize = 5;
        for (int i = 0; i <= testString.Length-1; i++)
        {
            chunkBuilder += testString[i];

            if (chunkBuilder.Length == chunkSize || i == testString.Length - 1)
            {
                result.Add(chunkBuilder);
                chunkBuilder = "";
            }
        }

答案 5 :(得分:0)

另一种尝试,使用较少的字符串连接

string Test = "This is a test string";
List<string> parts = new List<string>();
int i = 0; 
do
{
   parts.Add(Test.Substring(i,System.Math.Min(5, Test.Substring(i).Length))); 
   i+= 5;
} while (i < Test.Length);

答案 6 :(得分:0)

以下是一些方法。下面Cutup2效率更高,但不太漂亮。两者都通过了给出的测试用例。

private static IEnumerable<string> Cutup(string given, int chunkSize)
{
    var skip = 0;
    var iterations = 0;
    while (iterations * chunkSize < given.Length)
    {
        iterations++;                
        yield return new string(given.Skip(skip).Take(chunkSize).ToArray());
        skip += chunkSize;
    }
}

private static unsafe IEnumerable<string> Cutup2(string given, int chunkSize)
{
    var pieces = new List<string>();
    var consumed = 0;

    while (consumed < given.Length)
    {
        fixed (char* g = given)
        {
            var toTake = consumed + chunkSize > given.Length 
                         ? given.Length - consumed 
                         : chunkSize;

            pieces.Add(new string(g, consumed, toTake));
        }

        consumed += chunkSize;
    }

    return pieces;
}

答案 7 :(得分:0)

我曾经做过一个可用于此的扩展方法:

    public static IEnumerable<IEnumerable<T>> Subsequencise<T>(this IEnumerable<T> input, int subsequenceLength)
    {
        var enumerator = input.GetEnumerator();
        SubsequenciseParameter parameter = new SubsequenciseParameter { Next = enumerator.MoveNext() };
        while (parameter.Next)
            yield return getSubSequence(enumerator, subsequenceLength, parameter);

    }


    private static IEnumerable<T> getSubSequence<T>(IEnumerator<T> enumerator, int subsequenceLength, SubsequenciseParameter parameter)
    {
        do
        {
            yield return enumerator.Current;
        } while ((parameter.Next = enumerator.MoveNext()) && --subsequenceLength > 0);
    } 

    // Needed to let the Subsequencisemethod know when to stop, since you cant use out or ref parameters in an yield-return method.
    class SubsequenciseParameter
    {
        public bool Next { get; set; }
    }

然后你可以这样做:

string Test = "This is a test string";
stringarray = Test.Subsequencise(5).Select(subsequence => new String(subsequence.Toarray())).Toarray();

答案 8 :(得分:0)

全部在一行

        var size = 5;

        var results = Enumerable.Range(0, (int)Math.Ceiling(test.Length / (double)size))
                                .Select(i => test.Substring(i * size, Math.Min(size, test.Length - i * size)));

答案 9 :(得分:0)

这是一个相当LINQy的单行:

static IEnumerable<string> SliceAndDice1( string s , int n )
{
  if ( s == null ) throw new ArgumentNullException("s");
  if ( n < 1 ) throw new ArgumentOutOfRangeException("n");

  int i = 0 ;
  return s.GroupBy( c => i++ / n ).Select( g => g.Aggregate(new StringBuilder() , (sb,c)=>sb.Append(c)).ToString() ) ;
}

如果这让您头疼,请尝试更直接的

static IEnumerable<string> SliceAndDice2( string s , int n )
{
  if ( s == null ) throw new ArgumentNullException("s") ;
  if ( n < 1 ) throw new ArgumentOutOfRangeException("n") ;

  int i = 0 ;
  for ( i = 0 ; i < s.Length-n ; i+=n )
  {
    yield return s.Substring(i,n) ;
  }
  yield return s.Substring(i) ;

}