面试碰到一个这样的题------ 输入为一个字符串和字节数,输出为按字节截取的字符串

今天面试碰到这样一个面试题:

编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串。 但是要保证汉字不被截半个,如“我ABC”4,应该截为“我AB”,输入“我ABC汉DEF”,6,应该输出为“我ABC”而不是“我ABC+汉的半个”。

感觉很有意思,当时有点紧张思考了一会儿,写了个大概,回家想想了,写了个完整的。

代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Test1
{
class Program
{
static void Main(string[] args)
{
test s = new test();

Console.WriteLine(s.retStr("我是ABC大好人", 5));
Console.ReadKey();
}
}

}

class test
{

//判断是不是汉字
public bool IsHanZi(char str)
{
if ((int)str > 127)
{
return true;
}
else
{
return false;
}
}


//计算输入字符串的总字节数
public int strTotal(string str)
{
int len = 0;
char[] chr = str.ToCharArray();
for (int i = 0; i < chr.Length; i++)
{
if (IsHanZi(chr[i]))
{
len = len + 2;
}
else
{
len = len + 1;
}
}

return len;
}


public string retStr(string inputStr, int len)
{
if (inputStr == null || inputStr == "")
{
return "";
}

if (len == 0 || len > strTotal(inputStr))
{
return inputStr;
}

char[] chr = inputStr.ToCharArray();
string newStr = "";
int count = 0;
for (int i = 0; i < chr.Length; i++)
{
if (count < len)
{
if (IsHanZi(chr[i]))
{
if ((count + 1) == len)
return newStr;
count = count + 2;
newStr = newStr + chr[i].ToString();
}
else
{
count = count + 1;
newStr = newStr + chr[i].ToString();
}
}
}

return newStr;

}
}

原文地址:https://www.cnblogs.com/CskyWarrior/p/4079499.html