前几天投简历收到一份上机题,其中第一题我觉得还算经典的,搜索引擎上有人问类似问题,但是没有很好的回答。当然起初我并没有对C#有过深的研究,不免要查看翻阅很多资料。
题目大意如下:
要求用一个字符为标志分割字符串,但是要忽略引号(“)内部的分割字符。
所以这个就不再是简单的利用Split函数那么简单了。起初思路比较多,比较乱,总是想利用上Split函数以助我一臂之力,但是越是指望他越是出现很多纠结的地方。最终不得不利用遍历每个字符来对字符串进行处理。但是涉及到就不是简单的数组了,要用到ArrayList动态数组。更纠结的是数组内Object对象类型的转换。废话少说代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.ComponentModel;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
string str = “Technical;T_REU~!@#$%^&*()_+SEF_900;”Reuse factor; 900″;Number;1;Reuse factor 900”;//示例字符串
ArrayList temp = new ArrayList();
ArrayList chartemp = new ArrayList();
Boolean abort = false;
int count = 0;
int count2 =0;
foreach (char i in str)
{
if (i.Equals(‘”‘)) {
abort = !abort;
}
if (!i.Equals(‘”‘)&&!i.Equals(‘;’)) {
chartemp.Add(i);
}
if (!i.Equals(‘”‘) && i.Equals(‘;’)&&abort==true)
{
chartemp.Add(i);
}
if (i.Equals(‘;’)&&abort==false) {
string str5 = string.Join(null,(char[])chartemp.ToArray(typeof(char))); //其实这句是核心
temp.Add(str5);
chartemp.Clear();
}
}
string str6 = string.Join(null, (char[])chartemp.ToArray(typeof(char)));
temp.Add(str6);
chartemp.Clear();
foreach ( var i in temp) {
Console.WriteLine(i);
}
Console.ReadLine();
}
}
}
其实代码为简化,还可以做到复用性更强,但是由于最近是考试周,复习考试都很忙,所以懒得去改了。