【问题标题】:Why Is My Code Not Removing Whitespace Of String?为什么我的代码没有删除字符串的空格?
【发布时间】:2016-12-16 04:23:35
【问题描述】:

我有一个UITableView,它显示了一个用户列表。如果在返回的 JSON 中他们的display_name 是null,则显示他们的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

}

最后,我在单元格中显示用户的displayName 或socialNetworkHandle。如果displayName 是nil,则显示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 的开头显示为空格。以下屏幕截图说明了正在发生的事情:

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

【问题讨论】:

  • 你想用 Objc 还是 Swift 做出答案?

标签: ios string uitableview removing-whitespace


【解决方案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

}

希望对你有帮助

【讨论】:

  • @Reiner Melian 我喜欢你的解决方案!但是,你能告诉我为什么我的不工作吗?
  • @Reiner Melian 我实施了您的解决方案,但我得到的结果与实施前相同。
  • 你能把你的完整项目发给我吗?你原来的解决方案不起作用,因为method trimmingCharacters只删除了字符串开头和结尾的空格,最好的问候,我的电子邮件是 rmelian2014@gmail.com
  • 这正是我想要做的。我只想修剪前导和尾随空格。感谢您的帮助,但这个项目是针对与我签订合同的公司,所以我无法分享。
  • 在创建模型时尝试使用该方法,您可以在该方法工作之前和之后进行调试,同时检查您的单元格中的约束和标签水平对齐,我很确定我的方法有效,因为我现在在很多项目中都使用它
猜你喜欢
  • 1970-01-01
  • 2021-02-23
  • 1970-01-01
  • 1970-01-01
  • 2013-06-06
  • 1970-01-01
  • 2023-04-01
  • 2011-11-15
  • 2021-12-22
相关资源
最近更新 更多