当前位置:网站首页>C#如何打印輸出原版數組
C#如何打印輸出原版數組
2022-07-01 06:24: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]
最後文中若有不足,還請多多勘誤指正!
边栏推荐
- [ManageEngine Zhuohao] helps Huangshi Aikang hospital realize intelligent batch network equipment configuration management
- SystemVerilog learning-08-random constraints and thread control
- [postgraduate entrance examination advanced mathematics Wu Zhongxiang +880 version for personal use] advanced mathematics Chapter II Basic Stage mind map
- 三分钟带你快速了解网站开发的整个流程
- High order binary search tree
- Recueillir des trésors dans le palais souterrain (recherche de mémoire profonde)
- 连续四年入选Gartner魔力象限,ManageEngine卓豪是如何做到的?
- Factorial divisor (unique decomposition theorem)
- Uniapp tree level selector
- 【LeetCode】Day91-存在重复元素
猜你喜欢
Pit of kotlin bit operation (bytes[i] and 0xff error)
分布式锁实现
ArcServer密码重置(账号不可以重置)
[postgraduate entrance examination advanced mathematics Wu Zhongxiang +880 version for personal use] advanced mathematics Chapter II Basic Stage mind map
68 cesium code datasource loading czml
SystemVerilog learning-08-random constraints and thread control
IT服务管理(ITSM)在高等教育领域的应用
JMM details
HCM Beginner (IV) - time
B-tree series
随机推荐
ManageEngine Zhuohao helps you comply with ISO 20000 standard (IV)
Forkjoin and stream flow test
Golang panic recover custom exception handling
Projects and dependencies in ABP learning solutions
讓田頭村變甜頭村的特色農產品是仙景芋還是白菜
【自动化运维】自动化运维平台有什么用
Promise
【网络安全工具】USB控制软件有什么用
HCM Beginner (III) - quickly enter pa70 and pa71 to browse employee information PA10
[leetcode] day91- duplicate elements exist
Movable mechanical wall clock
网络爬虫
JMM详解
Understanding of C manualresetevent class
C语言课设物业费管理系统(大作业)
async 与 await
C语言课设工资管理系统(大作业)
SystemVerilog learning-06-class encapsulation
Make: g++: command not found
pycharm 配置jupyter