C#中将字符串转化为字符串数组

题目:将字符串转化为字符串数组,字符串中有“,”隔开,每一个“,”前面的内容形成每一组数组的每一段的内容。

代码如下:

1.用函数写:

using System;

namespace _3._14town
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = ",ab,cad,dd,edas,fasdwasd,gasdq,";//创建一个长度任意的数组
            string[] str1 = newstr(str);   //定义一个新的数组
            for (int i = 0; i < str1.Length; i++)
            {
                if (str1[i]!=null)        //遍历时,当输出为空的时候不输出,这样不会出现换行的情况
                {
                    Console.WriteLine(str1[i]);
                }               
            }
        }
        static string[] newstr(string str)     //创建一个数组的函数并使用
        {
            int count1 = count(str);             //获取数组的长度
            string[] str1 = new string[count1];//在C#中,数组的长度是不可更改的。一旦数组被创建,其长度就会被固定下来。
            int index = 0;//下标
            for (int i = 0;i < str.Length; i++)
            {
                if (str[i] == ',')      //当检测到“,”时,下标加一,数组内容不更新,继续进行循环
                {
                    index++;
                    continue;
                }
                str1[index] += str[i];    //将“,”前面的数据全部导入
            }
            return str1;           //返回数组
        }
        static int count(string str)    //定义一个设置数组长度的函数,并最终返回数组长度
        {
            int count1 = 0;
            for (int i = 0; i < str.Length; i++)   //将字符串内的所有非“,”的内容计数
            {
                if (str[i] != ',')
                {
                    count1++;
                }
            }
            return count1;
        }
    }
}

2.不用函数写:

using System;

namespace _3._14class
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = ",ab,cad,dd,edas,fasdwasd,gasdq,";
            int count = 0;
            int index = 0;
            for (int i = 0; i < str.Length; i++)
            {
                if (str[i] == ',')
                {
                    count++;
                }
            }
            string[] str1 = new string[count];    //在C#中,数组的长度是不可更改的。一旦数组被创建,其长度就会被固定下来。
            for (int i = 0; i < str.Length; i++)
            {
                if (str[i] == ',')
                {
                    index++;
                    continue;
                }
                str1[index] += str[i];
            }
            for (int i = 0; i < str1.Length; i++)
            {
                if (str1[i] != null)
                {
                    Console.WriteLine(str1[i]);
                }

            }
        }
    }
}

注意事项:

1.特别需要注意的地方为,数组长度一般被定义就不可以被更改,长度就会被固定下来。

2.输出时需要注意记得将null不输出。只将数组中有内容的数组输出。这样比较合理。

3.当用函数写的时候,需要注意返回值的内容。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值