[英]Remove first character from string if 0
I need to remove the first character from my UITextfield
if it's a 0.如果它是 0,我需要从我的
UITextfield
删除第一个字符。
Unfortunately I don't know how to extract the value of the first character or extract the characters of the string after the first character.不幸的是我不知道如何提取第一个字符的值或提取第一个字符之后的字符串的字符。
Thanks谢谢
One solution could be:一种解决方案可能是:
if ([string hasPrefix:@"0"] && [string length] > 1) {
string = [string substringFromIndex:1];
}
You would probably want something like this, using hasPrefix:你可能想要这样的东西,使用hasPrefix:
if ([string hasPrefix:@"0"]) {
string = [string substringFromIndex:1];
}
You could also use characterAtIndex: which returns a unichar:您还可以使用characterAtIndex:它返回一个 unichar:
if ([string characterAtIndex:0] == '0') {
string = [string substringFromIndex:1];
}
Note that, 'a' is character, "a" is C string and @"a" is NSString.请注意,'a' 是字符,"a" 是 C 字符串,@"a" 是 NSString。 They all are different types.
它们都是不同的类型。
Swift 3.0:斯威夫特 3.0:
var myString = "Hello, World"
myString.remove(at: myString.startIndex)
myString // "ello, World"
Swift 3斯威夫特 3
hasPrefix("0") check if the first character is 0 in txtField and remove it hasPrefix("0") 检查 txtField 中的第一个字符是否为 0 并将其删除
if (self.txtField.text?.hasPrefix("0"))! {
self.txtField.text?.remove(at(self.txtField.text?.startIndex)!)
}
SWIFT 5.0 you can use the following sequence function to check whether string starts with "0" or not SWIFT 5.0你可以使用下面的序列函数来检查字符串是否以“0”开头
if search.starts(with: "0") {
search.remove(at: search.startIndex)
print("After Trim search is",search)
} else {
print("First char is not 0")
}
Replace the string variable with your current variable name.
用您当前的变量名替换字符串变量。 I hope this helps you
我希望这可以帮助你
While loop to keep removing first character as long as it is zero只要第一个字符为零,While 循环就会继续删除它
while (self.ammountTextField.text?.hasPrefix("0"))! {
self.ammountTextField.text?.remove(at: (self.ammountTextField.text?.startIndex)!)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.