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


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

    编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串。 但是要保证汉字不被截半个,如“我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;

    }
    }

  • 相关阅读:
    15.6.6-sql字符串组装技巧
    15.5.26-linq to ef多级外链查询
    15.04.14-登录之后刷新AntiForgeryToken
    15.04.10-有意思的补码
    【每天进步一点】毒药和老鼠的研究
    MVC的JavaScriptResult使用
    15.03.28-有意思的位运算
    jQuery笔记三——text/html/val/attr/prop
    jQuery笔记二——基础/动画
    jquery笔记一——小问题+小技巧
  • 原文地址:https://www.cnblogs.com/CskyWarrior/p/4079499.html
Copyright © 2020-2023  润新知