简体   繁体   中英

Remove first character from string if 0

I need to remove the first character from my UITextfield if it's a 0.

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:

if ([string hasPrefix:@"0"]) {
    string = [string substringFromIndex:1];
}

You could also use characterAtIndex: which returns a unichar:

if ([string characterAtIndex:0] == '0') {
     string = [string substringFromIndex:1];
}

Note that, 'a' is character, "a" is C string and @"a" is NSString. They all are different types.

Swift 3.0:

var myString = "Hello, World"
myString.remove(at: myString.startIndex)

myString // "ello, World"

Swift 3

hasPrefix("0") check if the first character is 0 in txtField and remove it

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

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 (self.ammountTextField.text?.hasPrefix("0"))! {     
   self.ammountTextField.text?.remove(at: (self.ammountTextField.text?.startIndex)!)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM