C# 開發 字串切割(分割)插入 斷行符號/換行符號 函數
C# 開發 字串切割(分割)插入 斷行符號/換行符號 函數
資料來源: Copilot
C#線上編譯: https://dotnetfiddle.net/
詢問內容: 使用C# 開發一個函數 該函數可以輸入一個中英文混雜的字串 和 設定字串多長就插入換行符號
Code
using System;
using System.Text;
public class Program
{
public static void Main()
{
string input = "這是一個測試string,包含中英文混合的字串。";
int length = 4;
string result = InsertLineBreaks(input, length);
Console.WriteLine(result);
}
public static string InsertLineBreaks(string input, int length)//字串在固定長度插入換行符號的功能函數
{
if (string.IsNullOrEmpty(input) || length <= 0)
{
return input;
}
StringBuilder sb = new StringBuilder();
int currentLength = 0;
foreach (char c in input)
{
sb.Append(c);
currentLength += (c > 127) ? 2 : 1; // 中文字符佔兩個單位,英文字符佔一個單位
if (currentLength >= length)
{
sb.Append(Environment.NewLine);
currentLength = 0;
}
}
return sb.ToString().TrimEnd('\r','\n');//移除字串最後的換行符號
}
}
/*
這是
一個
測試
stri
ng,
包含
中英
文混
合的
字串
。
*/
One thought on “C# 開發 字串切割(分割)插入 斷行符號/換行符號 函數”
C# 設計一個函數 自動剔除字串中的所有換行符號 [Copilot]
using System;
using System.Text.RegularExpressions;
public class StringHelper
{
public static string RemoveNewLines(string input)
{
if (string.IsNullOrEmpty(input))
{
return input;
}
// 使用正則表達式移除換行符號
return Regex.Replace(input, @"\r\n|\r|\n", string.Empty);
}
}