我需要将sql转换为c#:基于字符串长度的人类可读字符串截断
请帮我将bellow sql代码转换为c#
DECLARE @String VARCHAR(MAX),
@Size TINYINT
SELECT @String =
'Hello my name is Jeff. I need some help on a project because right now this is how the application i am working with displays data.',
@Size = 30
;WITH Peso(Part, StartPos, SIZE)
AS (
SELECT 1,
1,
CAST(
@Size - CHARINDEX(
' ',
REVERSE(LEFT(SUBSTRING(@String, 1, @Size) + ' ', @Size))
) AS INT
)
UNION ALL
SELECT Part + 1,
StartPos + SIZE + 1,
CAST(
@Size - CHARINDEX(
' ',
REVERSE(
LEFT(
SUBSTRING(@String, StartPos + SIZE + 1, @Size) +
' ',
@Size
)
)
) AS INT
)
FROM Peso
WHERE StartPos + SIZE <= DATALENGTH(@String)
)
SELECT Part,
SUBSTRING(@String, StartPos, SIZE)
FROM Peso
ORDER BY Part
原始代码来自:http://weblogs.sqlteam.com/peterl/archive/2009/03/18/Human-readable-string-truncation.aspx
答案 0 :(得分:0)
我无法将其从sql转换为c#,因此,我编写了另一个代码:
public static IEnumerable<string> Split(string str, int chunkSize)
{
var list = str.Split(' ').ToList();
var buildList = new List<string>();
foreach (var s in list)
{
if (s.Length > chunkSize)
{
var x = SplitString(s, chunkSize);
buildList.AddRange(x);
}
else
{
buildList.Add(s);
}
}
var strResult = new List<string>();
for (int i = 0; i < buildList.Count; i++)
{
strResult.Add("");
}
int line = 0;
for (int i = 0; i < buildList.Count; i++)
{
if ((strResult[line] + " " + buildList[i]).Length > chunkSize + 1)
{
line++;
strResult[line] = buildList[i].Trim();
}
else
{
strResult[line] = (strResult[line] + " " + buildList[i]).Trim();
}
}
return strResult.Where(x => !string.IsNullOrEmpty(x)).ToList();
}
public static IEnumerable<string> SplitString(string str, int chunkSize)
{
return str.Select((x, i) => i)
.Where(i => i % chunkSize == 0)
.Select(i => str.Substring(i, str.Length - i >= chunkSize ? chunkSize : str.Length - i));
}
并使用如下:
string text = "Hel l33 3333333333333333333933 3333333333313333333333333333333335 ause right now this is how the application i am working with displays data.";
var ret = string.Join(Environment.NewLine, Split(text, 30));
快乐的编码!