• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Limiting NSString length without knowing the length
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Limiting NSString length without knowing the length


  • Subject: Limiting NSString length without knowing the length
  • From: Jeffrey Mattox <email@hidden>
  • Date: Thu, 13 Feb 2003 03:40:02 -0600

Executive summary:

Is there a NSString method that will truncate a string to a specified length without me having to know its length beforehand?


Details:

I have a NSString of an unknown length from which I create a second, formatted string that contains the first string. For example:

string2 = [NSString stringWithFormat:@"OLD: %@",string1];

However, I need to limit the length of string2 to a fixed value. The documentation says stringWithFormat: uses printf()-like formats, but specifying a precision of 20 does not work, like this:

string2 = [NSString stringWithFormat:@"OLD: %.20@", string1];

Apparently, stringWithFormat: doesn't implement all the printf() features.

So, I've looked at using this method:

[string1 substringToIndex:20]

But if the index is beyond the end of the string, it will raise an error. That forces me to test the length first if I want to use that method.

Unless I find a better way, this is my solution (convert to a C string, limit the length, and then convert back to NSString):

char theCString[30];
sprintf(theCString,"%.20s",[string1 cString]); // limit
string2 = [NSString stringWithFormat:@"OLD: %@",
[NSString stringWithCString:theCString]];

But, is there a better way -- a method that will truncate a NSString without me having to know its length beforehand?

Jeff
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives: http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.

  • Follow-Ups:
    • Re: Limiting NSString length without knowing the length
      • From: Marc Weil <email@hidden>
    • Re: Limiting NSString length without knowing the length
      • From: MacInsight <email@hidden>
  • Prev by Date: Re: Nightmare with NSTimer
  • Next by Date: Re: Limiting NSString length without knowing the length
  • Previous by thread: Re: Nightmare with NSTimer
  • Next by thread: Re: Limiting NSString length without knowing the length
  • Index(es):
    • Date
    • Thread