【发布时间】:2025-12-26 19:00:17
【问题描述】:
我有以下代码从未知长度的字符串中删除 5 个字符。
string latitudelength = latitude.Length.ToString(CultureInfo.InvariantCulture); //<<--Get length of string
int intLatitudeLength = Convert.ToInt32(latitudelength) -5; //<--Now substract 5 char from it
string trimLatitude = latitude.Remove(5, intLatitudeLength); //<-- now remove all chars after 5th
上面只是将一个未知长度的字符串修剪为 5 个字符似乎还有很长的路要走。
有没有更专业的方法?
谢谢
有人能解释一下为什么这篇文章被标记了,这里发布的很多例子都使用子字符串,如果字符串的长度是已知的,那么子字符串就可以了,但是字符串的长度是未知的,所以子字符串不能使用。
我的示例计算字符串的长度,然后删除所需的字符数。
我的问题明确问有没有更专业的方式。
我已经清理了我的代码,希望它可以在未来帮助任何人
string latitudelength = latitude.Length.ToString(CultureInfo.InvariantCulture);
int intLatitudeLength = Convert.ToInt32(latitudelength);
string trimLatitude = intLatitudeLength > 5 ? latitude.Substring(0,5) : latitude;
它现在检查字符串的长度,如果超过 5 个字符使用子字符串,如果少于则显示纬度等。如果字符串为空,我没有添加代码
【问题讨论】:
-
为什么不
latitude.SubString(0, 5);? -
我很好奇你为什么将
latitude的长度转换为字符串然后再转换回整数。 -
Hi Cuong Le 如果字符串只有 4 个字符会发生什么,它会抛出错误
-
嗨,Eric,因为这是我可以将 intLatitudeLength 添加到 trimLatitude 而不会导致错误的唯一方法
-
你是对的,我使用
Take添加新答案