String truncation method with fixed length (C #)

Source: Internet
Author: User
String truncation method with fixed length (C #)

There is nothing special about this function, that is, it can intercept strings of a certain length. It may be a small feature that Len is a byte, which solves the problem that different Chinese characters and English bytes lead to different lengths directly intercepted.

 

1 string truncation function # region string truncation Function
2 public static string cutstring (string inputstring, int Len)
3 {
4
5
6 asciiencoding ASCII = new asciiencoding ();
7int templen = 0;
8 string tempstring = "";
9 byte [] S = ASCII. getbytes (inputstring );
10for (INT I = 0; I <S. length; I ++)
11 {
12If (INT) s [I] = 63)
13 {
14 templen + = 2;
15}
16 else
17 {
18 templen + = 1;
19}
20
21try
22 {
23 tempstring + = inputstring. substring (I, 1 );
24}
25 catch
26 {
27 break;
28}
29
30if (templen> Len)
31 break;
32}
33 // If yes, add half ellipsis
34 byte [] mybyte = system. Text. encoding. Default. getbytes (inputstring );
35if (mybyte. length> Len)
36 tempstring + = "... ";
37
38
39 return tempstring;
40}
41 # endregion
42

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.