ios 如何创建带格式的字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24074479/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 00:35:10  来源:igfitidea点击:

How to create a string with format?

iosswiftios8

提问by Apurv

I need to create a string with format which can convert int, long, double etc. types into string. Using Obj-C, I can do it via below way.

我需要创建一个字符串,其格式可以将 int、long、double 等类型转换为字符串。使用 Obj-C,我可以通过以下方式完成。

NSString *str = [NSString stringWithFormat:@"%d , %f, %ld, %@", INT_VALUE, FLOAT_VALUE, DOUBLE_VALUE, STRING_VALUE];

How to do same with swift?

如何用 swift 做同样的事情?

回答by realityone

I think this could help you:

我认为这可以帮助你:

let timeNow = time(nil)
let aStr = String(format: "%@%x", "timeNow in hex: ", timeNow)
print(aStr)

Example result:

结果示例:

timeNow in hex: 5cdc9c8d

回答by Bryan Chen

nothing special

没什么特别的

let str = NSString(format:"%d , %f, %ld, %@", INT_VALUE, FLOAT_VALUE, LONG_VALUE, STRING_VALUE)

回答by John Estropia

let str = "\(INT_VALUE), \(FLOAT_VALUE), \(DOUBLE_VALUE), \(STRING_VALUE)"

Update:I wrote this answer before Swift had String(format:)added to it's API. Use the method given by the top answer.

更新:我在 SwiftString(format:)添加到它的 API之前写了这个答案。使用顶级答案给出的方法。

回答by Durul Dalkanat

No NSStringrequired!

不需要NSString

String(format: "Value: %3.2f\tResult: %3.2f", arguments: [2.7, 99.8])

or

或者

String(format:"Value: %3.2f\tResult: %3.2f", 2.7, 99.8)

回答by Lance Clark

I would argue that both

我认为两者都

let str = String(format:"%d, %f, %ld", INT_VALUE, FLOAT_VALUE, DOUBLE_VALUE)

and

let str = "\(INT_VALUE), \(FLOAT_VALUE), \(DOUBLE_VALUE)"

are both acceptable since the user asked about formatting and both cases fit what they are asking for:

都是可以接受的,因为用户询问了格式并且这两种情况都符合他们的要求:

I need to create a string with format which can convert int, long, double etc. types into string.

我需要创建一个字符串,其格式可以将 int、long、double 等类型转换为字符串。

Obviously the former allows finer control over the formatting than the latter, but that does not mean the latter is not an acceptable answer.

显然,前者比后者允许更好地控制格式,但这并不意味着后者不是可接受的答案。

回答by Apple

var str = "\(INT_VALUE) , \(FLOAT_VALUE) , \(DOUBLE_VALUE), \(STRING_VALUE)"

回答by iPatel

First read Official documentation for Swift language.

首先阅读Swift 语言的官方文档。

Answer should be

答案应该是

var str = "\(INT_VALUE) , \(FLOAT_VALUE) , \(DOUBLE_VALUE), \(STRING_VALUE)"
println(str)

Here

这里

1) Any floating point value by default double

1) 默认任何浮点值 double

EX.
 var myVal = 5.2 // its double by default;

-> If you want to display floating point value then you need to explicitly define such like a

-> 如果你想显示浮点值,那么你需要明确定义这样的

 EX.
     var myVal:Float = 5.2 // now its float value;

This is far more clear.

这要清楚得多。

回答by Awais Chatha

let INT_VALUE=80
let FLOAT_VALUE:Double= 80.9999
let doubleValue=65.0
let DOUBLE_VALUE:Double= 65.56
let STRING_VALUE="Hello"

let str = NSString(format:"%d , %f, %ld, %@", INT_VALUE, FLOAT_VALUE, DOUBLE_VALUE, STRING_VALUE);
 println(str);

回答by dede.exe

I know a lot's of time has passed since this publish, but I've fallen in a similar situation and create a simples class to simplify my life.

我知道自发布以来已经过去了很多时间,但我陷入了类似的境地,并创建了一个简单的类来简化我的生活。

public struct StringMaskFormatter {

    public var pattern              : String    = ""
    public var replecementChar      : Character = "*"
    public var allowNumbers         : Bool      = true
    public var allowText            : Bool      = false


    public init(pattern:String, replecementChar:Character="*", allowNumbers:Bool=true, allowText:Bool=true)
    {
        self.pattern            = pattern
        self.replecementChar    = replecementChar
        self.allowNumbers       = allowNumbers
        self.allowText          = allowText
    }


    private func prepareString(string:String) -> String {

        var charSet : NSCharacterSet!

        if allowText && allowNumbers {
            charSet = NSCharacterSet.alphanumericCharacterSet().invertedSet
        }
        else if allowText {
            charSet = NSCharacterSet.letterCharacterSet().invertedSet
        }
        else if allowNumbers {
            charSet = NSCharacterSet.decimalDigitCharacterSet().invertedSet
        }

        let result = string.componentsSeparatedByCharactersInSet(charSet)
        return result.joinWithSeparator("")
    }

    public func createFormattedStringFrom(text:String) -> String
    {
        var resultString = ""
        if text.characters.count > 0 && pattern.characters.count > 0
        {

            var finalText   = ""
            var stop        = false
            let tempString  = prepareString(text)

            var formatIndex = pattern.startIndex
            var tempIndex   = tempString.startIndex

            while !stop
            {
                let formattingPatternRange = formatIndex ..< formatIndex.advancedBy(1)

                if pattern.substringWithRange(formattingPatternRange) != String(replecementChar) {
                    finalText = finalText.stringByAppendingString(pattern.substringWithRange(formattingPatternRange))
                }
                else if tempString.characters.count > 0 {
                    let pureStringRange = tempIndex ..< tempIndex.advancedBy(1)
                    finalText = finalText.stringByAppendingString(tempString.substringWithRange(pureStringRange))
                    tempIndex = tempIndex.advancedBy(1)
                }

                formatIndex = formatIndex.advancedBy(1)

                if formatIndex >= pattern.endIndex || tempIndex >= tempString.endIndex {
                    stop = true
                }

                resultString = finalText

            }
        }

        return resultString
    }

}

The follow link send to the complete source code: https://gist.github.com/dedeexe/d9a43894081317e7c418b96d1d081b25

以下链接发送至完整源代码:https: //gist.github.com/dedeexe/d9a43894081317e7c418b96d1d081b25

This solution was base on this article: http://vojtastavik.com/2015/03/29/real-time-formatting-in-uitextfield-swift-basics/

此解决方案基于本文:http: //vojtastavik.com/2015/03/29/real-time-formatting-in-uitextfield-swift-basics/

回答by Paula Hasstenteufel

There is a simple solution I learned with "We <3 Swift" if you can't either import Foundation, use round()and/or does not want a String:

如果您不能导入 Foundation、使用round()和/或不想要String,我从“We <3 Swift”中学到了一个简单的解决方案:

var number = 31.726354765
var intNumber = Int(number * 1000.0)
var roundedNumber = Double(intNumber) / 1000.0

result: 31.726

结果:31.726