当前位置:网站首页>C#如何打印输出原版数组
C#如何打印输出原版数组
2022-07-01 06:20:00 【SteveDraw】
前言:
数组是一个非常重要的数据结构,我们经常会使用到它,可能最长用到的是遍历并打印它们,但是有个小问题我们边遍历边打印,往往会外形不会像原本的结构!
- 以一个数组为例,该数组结构例如:
int [] b= new int []{
1,2,3}
- 以调用换行打印函数为例(单行打印也一样,只是为了说明情况),打印输入如下:
1
2
3
这样我们如果同时使用其他数组结构并打印到CLI上就会影响判断和阅读,这样看来我们打印时需要还原成数组在代码定义时的模样!
解决方法
我们需要写一个专门输出特定数组类型的打印函数才行!Easy!直接上代码!
(1)函数方法
static void PrintArray(int[] a)//具体数组类型可根据实际更改
{
//需要对输入数组判断是否为空
if (a.Length != 0)
{
string str = "";
foreach (var i in a)
{
str = str + i + ",";
}
WriteLine("[" + str.Substring(0, str.Length - 1) + "]");//通过Substring()去除对应字符
}
if (a.Length == 0) WriteLine("[]");//如果数组为空,打印空数组格式即可
}
如果经常使用,在类库项目中,将函数封装成类方法,那将会优化你的效率!
(2)完整代码(附带测试代码):
using static System.Console;
namespace ConsoleApp1
{
class Program
{
static void PrintArray(int[] a)//具体数组类型可根据实际更改
{
//需要对输入数组判断是否为空
if (a.Length != 0)
{
string str = "";
foreach (var i in a)
{
str = str + i + ",";
}
WriteLine("[" + str.Substring(0, str.Length - 1) + "]");//通过Substring()去除对应字符
}
if (a.Length == 0) WriteLine("[]");//如果数组为空,打印空数组格式即可
}
static void Main(string[] args)
{
int[] a=new int[] {
1,2,3};
PrintArray(a);
ReadKey();
}
}
}
- 输出如下:
[1,2,3]
最后文中若有不足,还请多多勘误指正!
边栏推荐
- 地宮取寶(記憶化深搜)
- Although pycharm is marked with red in the run-time search path, it does not affect the execution of the program
- [automatic operation and maintenance] what is the use of the automatic operation and maintenance platform
- Servlet
- SQL语句
- Kubedm builds kubenetes cluster (Personal Learning version)
- 连续四年入选Gartner魔力象限,ManageEngine卓豪是如何做到的?
- [ITSM] what is ITSM and why does it department need ITSM
- Self confidence is indispensable for technology
- 【ManageEngine卓豪】用统一终端管理助“欧力士集团”数字化转型
猜你喜欢
随机推荐
Self confidence is indispensable for technology
记磁盘扇区损坏导致的Mysql故障排查
Make Tiantou village sweet. Is Xianjing taro or cabbage the characteristic agricultural product of Tiantou Village
指数法和Random Forest实现山东省丰水期地表水体信息
阶乘约数(唯一分解定理)
SOE空间分析服务器 MySQL以及PostGres的地理空间库PostGIS防注入攻击
Ant new village is one of the special agricultural products that make Tiantou village in Guankou Town, Xiamen become Tiantou village
SystemVerilog learning-10-validation quantification and coverage
[network security tool] what is the use of USB control software
Servlet
SystemVerilog learning-09-interprocess synchronization, communication and virtual methods
码力十足学量化|如何在财务报告寻找合适的财务公告
证券类开户有什么影响 开户安全吗
kotlin位运算的坑(bytes[i] and 0xff 报错)
async 与 await
Factorial divisor (unique decomposition theorem)
SOE spatial analysis server MySQL and PostGIS geospatial database of Postgres anti injection attack
扩散(多源广搜)
Distributed lock implementation
JDBC database operation









