-3

I have a variety of NSStrings that could be for example:

NSString *string = [NSString stringWithFormat:@"Item Used %@ times",item.numberOfUses];

or

NSString *string = [NSString stringWithFormat:@"Created %@ items",item.count];

Main point being, the amount of characters is always different. What I need to do is calculate the number of characters, including whitespace, from the start of the string, up-to, but not including the '%@' and have that value as an integer.

I've attempted looking into NSScanner but so far am failing. Whats the correct way to do this?

cheers.

f.perdition
  • 205
  • 2
  • 14
  • 1
    NSScanner will work. Show your code! – matt Apr 23 '13 at 01:18
  • 3
    Uh, `%@` should not be used to display an integer. – Hot Licks Apr 23 '13 at 01:26
  • 2
    What are you trying to do here?? One suspects you're trying to do something the hard way when there's an easier way. – Hot Licks Apr 23 '13 at 01:27
  • 3
    And why can't you use `[theLiteralFormatString rangeOfString:@"%@"]`? – Hot Licks Apr 23 '13 at 01:30
  • 2
    I think we can all agree the question is a bit nutty as posed. – matt Apr 23 '13 at 01:33
  • I think the OP needs to provide a MUCH better explanation of what he wants to do AND WHY. – Hot Licks Apr 23 '13 at 01:34
  • Okay sorry i haven't been clear (its 2am!) im using %@ because i was pulling the value from core data. The reason i'm trying to do this is because im using NSAttributedString to change the colour of the text when the number is displayed so i need to set the range of characters that come before it for it to work. Given that the string is different each time, but always contains text followed by a number, i needed a way of working it out. Hope that makes sense – f.perdition Apr 23 '13 at 01:57
  • So what's wrong with `rangeOfString`? (And I hope you're not really trying to display an integer with `%@`.) – Hot Licks Apr 23 '13 at 02:07

1 Answers1

1

Can't you just store the first part in an NSString, ask for its length and then add it in the formatted string? Like this:

NSString * firstPart = @"Item Used ";
int length = [firstPart length];

NSString *string = [NSString stringWithFormat:@"%@%d times", firstPart, item.numberOfUses];
tim k
  • 162
  • 1
  • 9
  • Yes, it's weird that he's asking to extract the integer from the string when we *know* what the integer is because we *formed* the string: it's `item.numberOfUses` or `item.count`. However, this can happen if what you've got is, say, a button title or label in the interface. – matt Apr 23 '13 at 01:25
  • No he's asking for the number of characters before the int you are talking about! – tim k Apr 23 '13 at 01:30