修剪 NSString 而不扩展它

发布于 2024-11-09 10:37:16 字数 395 浏览 0 评论 0原文

我想将字符串修剪为 50 个字符(如果它太长),所以我决定使用以下方法。

someString = [someString stringByPaddingToLength: 50 withString: @"" startingAtIndex: 0];

我可以在 withString 参数后传递一个空字符串吗?当该方法尝试添加字符串直到 someString 长度达到 50 个字符时,我不想让我的应用程序崩溃。我担心这会很糟糕,因为它必须迭代字符串 [someString length] / 0 次。

我应该使用 nil 来代替还是寻找另一种方法来进行修剪?

谢谢。

I want to trim a string to 50 characters (if it's too long), so I decided to use the following method.

someString = [someString stringByPaddingToLength: 50 withString: @"" startingAtIndex: 0];

Can I pass an empty string after the withString argument? I don't want to crash my app when the method tries to add the string until someString is 50 characters in length. I'm afraid it's gonna be bad because it will have to iterate the string [someString length] / 0 times.

Should I use nil instead or search for another way to do the trimming?

Thank you.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

锦爱 2024-11-16 10:37:16

如果您想修剪字符串,我不太确定为什么要使用 stringByPaddingToLength:... 方法。我本以为 substringToIndex: NSString 方法将是一个更合乎逻辑的解决方案。

例如:

NSString *testString = @"This is a test string that contains over fifty characters. Exciting, yet true.";

if([testString length] > 50) {
    // The source string is long enough to grab a substring of.
    NSString *truncatedString = [testString substringToIndex:50];
}
else {
    // The source string is already less than fifty characters.
    NSString *truncatedString = [NSString stringWithString:testString];
}

I'm not quite sure why you're using the stringByPaddingToLength:... method, if you want to trim a string. I'd have thought that the substringToIndex: NSString method would be a more logical solution.

For example:

NSString *testString = @"This is a test string that contains over fifty characters. Exciting, yet true.";

if([testString length] > 50) {
    // The source string is long enough to grab a substring of.
    NSString *truncatedString = [testString substringToIndex:50];
}
else {
    // The source string is already less than fifty characters.
    NSString *truncatedString = [NSString stringWithString:testString];
}
知足的幸福 2024-11-16 10:37:16

为什么不使用 -[NSString substringToIndex:]

why not use -[NSString substringToIndex:]?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文