0

I am getting string in the following format.

ListName|Definition|Answer

And How want to separate it like :

String1 : ListName

String2 : Definition

String3 : Answer

Here, this words can be deffer as per the change in value.

So at any other point it may be like Hey|Name|Bye.

But | is always in the string.

And Is it Possible to count number of | in the string ?

How do I separate it ?

Devang
  • 11,258
  • 13
  • 62
  • 100

5 Answers5

2

you can separate it like :

NSString *string = @"ListName|Definition|Answer";
NSArray *chunks = [string componentsSeparatedByString: @"|"];

now you have an array like:

chunk[0] = ListName
chunk[1] = Definition
chunk[2] = Answer

Hope it helps you....

Maulik
  • 19,348
  • 14
  • 82
  • 137
2

The method you are looking for is built into the NSString class. The documentation for the class can be found here.

The method to use would be.

- (NSArray *)componentsSeparatedByString:(NSString *)separator

//An example of this in action
NSString *exampleString = @"Test|some|strings";

NSArray *separatedStrings = [exampleString componentsSeparatedByString:@"|"];

At this point you can do whatever you would like with each string in the array such as iterating over it or accessing a specific string in the sequence.

I've included an example of iterating over the elements returned for reference.

//This for example is a nice use of the NSArray enumeration
//Much easier than the standard for loop with multiple parameters
for(NSString *aComponent in separatedStrings) {
   NSLog(@"A piece is: %@", aComponent);
   //Do something with each string
}
Hazmit
  • 165
  • 6
2

Use this:

NSArray *comps = [string componentsSeparatedByString: @"|"];
NSString *listName = [comps objectAtIndex:0];
NSString *definition = [comps objectAtIndex:1];
NSString *answer = [comps objectAtIndex:2];
akashivskyy
  • 44,342
  • 16
  • 106
  • 116
  • I think the 'NSString *answer = [comps objectAtIndex:3];' should be 'NSString *answer = [comps objectAtIndex:2];' :) – Michael Bai Aug 19 '11 at 08:05
2

Below is the entire code:

NSArray *array = [string componentsSeparatedByString: @"|"];

NSMutableArray *mutableArray = [NSMutableArray arrayWithArray: array];

for(int i=0; i<[mutableArray count]; i++)
{
    NSString *strData = [mutableArray objectAtIndex:i];
    NSLog(@"%@",strData);
}

Cheers.

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

build an array for your input string

  NSArray *strArray = [string componentsSeparatedByString: @"|"];

and then fill all the nsstrings from this array.

mayuur
  • 4,736
  • 4
  • 30
  • 65