题目:将字符串转化为字符串数组,字符串中有“,”隔开,每一个“,”前面的内容形成每一组数组的每一段的内容。
代码如下:
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.当用函数写的时候,需要注意返回值的内容。