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

时间:2016-12-15 19:15:42

标签: 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

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

1 个答案:

答案 0 :(得分:1)

这是Objc代码,这是NSString

的类别

目标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相同类别

夫特

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

}

我希望这有助于你