How to create a string with format?

2019-05-13 03:55发布

我需要创建,它可以转换的int,long双等类型转换为字符串格式的字符串。 使用的OBJ-C,我可以通过下面的方式做到这一点。

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

如何做同样与SWIFT?

Answer 1:

我认为这可以帮助你:

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


Answer 2:

没什么特别的

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


Answer 3:

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

更新:我写这个答案斯威夫特收到String(format:)加入到它的API。 使用由给定的方法顶部的答案 。



Answer 4:

没有NSString需要!

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

要么

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


Answer 5:

我认为,这两个

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

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

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

我需要创建,它可以转换的int,long双等类型转换为字符串格式的字符串。

显然,前者允许在格式比后者更精细的控制,但是,这并不意味着后者不是一个可以接受的答案。



Answer 6:

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


Answer 7:

首先阅读了雨燕语言官方文档。

答案应该是

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

这里

1)默认的任何浮点值double

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

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

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

这是更为清晰。



Answer 8:

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);


Answer 9:

我知道很多的时间的已经过去了,因为这发布,但我已经爱上了类似的情况,并创建一个simples类来简化我的生活。

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
    }

}

后续的链接发送给完整的源代码: https://gist.github.com/dedeexe/d9a43894081317e7c418b96d1d081b25

该解决方案是这篇文章的基础: http://vojtastavik.com/2015/03/29/real-time-formatting-in-uitextfield-swift-basics/



Answer 10:

使用此下面的代码:

    let intVal=56
    let floatval:Double=56.897898
    let doubleValue=89.0
    let explicitDaouble:Double=89.56
    let stringValue:"Hello"

    let stringValue="String:\(stringValue) Integer:\(intVal) Float:\(floatval) Double:\(doubleValue) ExplicitDouble:\(explicitDaouble) "


Answer 11:

有一个简单的解决方案,我用学到“我们<3雨燕”如果你也不能进口基金会 ,使用圆形()和/或不想要一个字符串

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

结果:31.726



Answer 12:

成功尝试一下:

 var letters:NSString = "abcdefghijkl"
        var strRendom = NSMutableString.stringWithCapacity(strlength)
        for var i=0; i<strlength; i++ {
            let rndString = Int(arc4random() % 12)
            //let strlk = NSString(format: <#NSString#>, <#CVarArg[]#>)
            let strlk = NSString(format: "%c", letters.characterAtIndex(rndString))
            strRendom.appendString(String(strlk))
        }


文章来源: How to create a string with format?
标签: ios swift ios8