当前位置:网站首页>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]
最后文中若有不足,还请多多勘误指正!
边栏推荐
- 地宮取寶(記憶化深搜)
- Redis安装到Windows系统上的详细步骤
- Factorial divisor (unique decomposition theorem)
- SQL语句
- To sort out the anomaly detection methods, just read this article!
- ForkJoin和Stream流测试
- ABP 学习解决方案中的项目以及依赖关系
- FPGA - clocking -02- clock wiring resources of internal structure of 7 Series FPGA
- Functions of switch configuration software
- C语言课设学生考勤系统(大作业)
猜你喜欢
随机推荐
【自动化运维】自动化运维平台有什么用
B-tree series
【KV260】利用XADC生成芯片温度曲线图
[summary of knowledge points] chi square distribution, t distribution, F distribution
SQL语句
[ITSM] what is ITSM and why does it department need ITSM
SQL中DML语句(数据操作语言)
图片服务器项目测试
让田头村变甜头村的特色农产品是仙景芋还是白菜
High order binary search tree
三分钟带你快速了解网站开发的整个流程
Although pycharm is marked with red in the run-time search path, it does not affect the execution of the program
69 cesium code datasource loading geojson
FPGA - 7 Series FPGA internal structure clocking-01-clock Architecture Overview
Diffusion (multi-source search)
C语言课设学生信息管理系统(大作业)
SystemVerilog learning-09-interprocess synchronization, communication and virtual methods
ManageEngine卓豪助您符合ISO 20000标准(四)
Transformer le village de tiantou en un village de betteraves sucrières
[leetcode] day91- duplicate elements exist









