ios - 为什么我的代码没有删除字符串的空格?

标签 ios string uitableview removing-whitespace

我有一个显示用户列表的UITableView。如果返回的 JSON 中他们的 display_namenull,则会显示他们的 socialNetworkHandle。但是,当我设置要修剪的空格时,我无法弄清楚为什么有些用户在字符串开头留下包含空格的 displayName

首先是保存用户信息的结构:

internal struct UserInformation {

    let socialNetworkHandle: String
    var displayName: String? = nil

    internal init?(socialNetworkHandle: String, displayName: String? = nil) {
        self.socialNetworkHandle = socialNetworkHandle
        self.displayName = displayName
    }

}

接下来是我解析 JSON 以创建用户信息结构的代码:

private func userInformation(from jsonDictionary: JSONDictionary) -> FeedwallPost.UserInformation? {

    // ...Some parsing code...

    var userInformation = Post.UserInformation()

    if let displayName = jsonDictionary["display_name"] as? String {
        userInformation?.displayName = displayName
    } else {
        print("`displayName` is not of type `String`")
    }

    // ...Some parsing code...

    return userInformation

}

最后,我在单元格中显示用户的 displayNamesocialNetworkHandle。如果 displayNamenil,则显示 socialNetworkHandle:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    /// ...Cell configuration code...

    cell.textLabel?.text = post.userInformation.displayName?.trimmingCharacters(in: .whitespaces) ?? post.userInformation.socialNetworkHandle.trimmingCharacters(in: .whitespaces)

    /// ... Cell configuration code...


    return cell

}

我一直遇到的问题是,当我修剪显示时,用户在其 displayName 的开头显示空格。以下屏幕截图说明了正在发生的情况:

Screenshot of iPhone displaying users

谁能告诉我我做错了什么?

最佳答案

这是Objc代码,这是NSString类的类别

objective-C

#import "NSString+CustomTrimming.h"

@implementation NSString (CustomTrimming)

/***
 Remove unnecesary spaces between the words, ex: @"asd      asdasdas"
 */
- (NSString*)stringRemovingUnnecessarySpaces
{
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@" +" options:0 error:NULL];
    NSString *newString = [regex stringByReplacingMatchesInString:self options:0 range:NSMakeRange(0, [self length]) withTemplate:@" "];
    newString = [newString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    return newString;
}

这和swift的分类是一样的

swift

import UIKit

extension String{

    func removingUnnecesarySpaces() ->String
    {  do
    {
        let regex = try NSRegularExpression(pattern: " +", options: NSRegularExpression.Options(rawValue: UInt(0)))
        var newString = regex .stringByReplacingMatches(in: self, options: NSRegularExpression.MatchingOptions.init(rawValue: 0), range: NSMakeRange(0, self.characters.count), withTemplate: " ")
        newString = newString.trimmingCharacters(in: CharacterSet.whitespaces)
        return newString
    }
    catch
    {

    }
        return self
    }
}

用这个例子

    debugPrint("  prueba     esto     ".removingUnnecesarySpaces())
    debugPrint(" prueba esto     ahora".removingUnnecesarySpaces())

控制台日志打印此内容

    "prueba esto"
    "prueba esto ahora"

在您的具体情况下,您只需用此替换代码

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    /// ...Cell configuration code...

    cell.textLabel?.text = post.userInformation.displayName?.removingUnnecesarySpaces() ?? post.userInformation.socialNetworkHandle.removingUnnecesarySpaces()

    /// ... Cell configuration code...


    return cell

}

希望对你有帮助

关于ios - 为什么我的代码没有删除字符串的空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41171710/

相关文章:

ios - UITableView - 使用 Hpple 数据设置表格 View

ios - 如何在 Objective-C 中使用局部变量作为 tableView 的数据源

ios - 滚动时保持 UITableViewCells 的选定状态

java.lang.ClassCastException : java. lang.Float 无法转换为 java.lang.String

c++ - 为什么 Microsoft 的 std::string 实现需要堆栈上的 40 个字节?

iphone - LinkedIn 菜单 iPhone 应用程序

ios - getter 和 setter 自定义并发队列同步的竞争条件

c - 字符数组是在 C 中表示字符串常量的另一种方式吗?

ios - Swift 将 UIImage 转换为没有 alpha channel 的 24 位 RGB

ios - Swift:获取结果集中的行数