18

I am using NSString and I want to get a substring of it that contains the first 20 characters of my string. How can I do that?

Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
MouzmiSadiq
  • 2,069
  • 3
  • 18
  • 21
  • This is way too easily Google-able. – Bijoy Thangaraj Feb 08 '13 at 06:55
  • Try this http://stackoverflow.com/questions/6440187/get-substring-from-nsstring, http://stackoverflow.com/questions/3613591/finding-a-substring-in-a-nsstring-object, http://stackoverflow.com/questions/5676106/how-to-get-substring-of-nsstring – laxonline Feb 08 '13 at 06:56
  • for get particular 20 characters from some stating characters to some last characters then check my this answer http://stackoverflow.com/questions/13415776/extract-substring-from-nsstring/13415868#13415868 – Paras Joshi Feb 08 '13 at 07:01

5 Answers5

49

You can use substringToIndex.

NSString *mystring = @"This is a test message having more than 20 characters";
NSString *newString = [mystring substringToIndex:20];
NSLog(@"%@", newString);
Bijoy Thangaraj
  • 5,434
  • 4
  • 43
  • 70
  • 6
    actually it is a good practice that you check the string length before substring NSString *newString = myString.length > 20 ? [mystring substringToIndex:20] : myString; – flyerz Jun 25 '14 at 00:14
35
NSString *str = @"123456789012345678901234";
NSString *subStr = [str substringWithRange:NSMakeRange(0, 20)];
Inder Kumar Rathore
  • 39,458
  • 17
  • 135
  • 184
1
NSString *string = @"I am having a simple question.I am having NSString and i want a substring of it that contains first 20 ";
NSString *first20CharString = [string substringToIndex:20];
Rushi
  • 4,553
  • 4
  • 33
  • 46
1

Try this:

NSString *string = @"This is for testing substring from string";
    NSInteger intIndex = 20;
    NSLog(@"%@", [string substringToIndex:intIndex]);
halfer
  • 19,824
  • 17
  • 99
  • 186
P.J
  • 6,547
  • 9
  • 44
  • 74
0

Check with below:

NSString *strTmp = @"This is test string to check substring.";
NSInteger intIdx = 20;
NSLog(@"%@", [strTmp substringToIndex:intIdx]);

It will be helpful to you.

Cheers!

Nishant B
  • 2,897
  • 1
  • 18
  • 25