how to use stringWithFormat to dynamically add hyphens into my string
Hi just wondering if it is possible, as the user is entering a string of numbers to dynamically add a hyphen every 5th character of the string...
any help would be greatly appr开发者_开发技巧eciated.
Try this code.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSString *separator = @"-";
int seperatorInterval = 5;
NSString *originalString = [textField.text stringByReplacingOccurrencesOfString:separator withString:@""];
if (![originalString isEqualToString:@""] && ![string isEqualToString:@""]) {
NSString *lastChar = [textField.text substringFromIndex:[textField.text length] - 1];
int modulus = [originalString length] % seperatorInterval;
if (![lastChar isEqualToString:separator] && modulus == 0) {
textField.text = [textField.text stringByAppendingString:separator];
}
}
return YES;
}
Assuming you are using a UITextField for input, you can use the UITextFieldTextDidChangeNotification
action to respond each time the text is modified. A quick and rough example:
- (IBAction)textChanged:(UITextField*)sender
{
NSString* curText = sender.text;
//when checking the length, you need to exclude hyphens from the count
//which is currently not being done (thanks @titaniumdecoy)
if([curText length] % 5 == 0)
{
sender.text = [curText stringByAppendingString:@"-"];
}
}
Just declare and alloc a 2 strings. Store the numbers in one string(str 1) and count the string length every entry. Check when the string lenght will four digit, perform
str2 = [str1 appendByString:@"`"];
now str1 = str2;
again repeat this process in loop with increment of 4 digit.
Hopes it will help.
Just a concept try to make substrings of each 5 characters then append a hyphen to these then concatenate each one. for this you need to make an array of substrings.use this logical function
-(NSString *)makeMyString:(NSString *)stringA
{
NSMutableArray *tempArray1=[NSMutableArray array];
//NSString *s=@"12345123451234512";
NSString *s=stringA;
BOOL flag=YES;
while(flag)
{
NSString *str;
if([s length]>=5)
str=[s substringWithRange:NSMakeRange(0,5)];
else
str=s;
[tempArray1 addObject:str];
str=nil;
if([s length]>=5)
s=[s substringWithRange:NSMakeRange(5,([s length]-5))];
else
s=@"";
if([s isEqualToString:@""])
flag=NO;
}
NSString *makeString=@"";
for(int i=0;i<[tempArray1 count];i++)
{
if([[tempArray1 objectAtIndex:i] length]==5)
makeString =[NSString stringWithFormat:@"%@%@`",makeString,[tempArray1 objectAtIndex:i]];
else {
makeString =[NSString stringWithFormat:@"%@%@",makeString,[tempArray1 objectAtIndex:i]];
}
}
NSLog(@"%@",makeString);
return makeString;
}
精彩评论