Split NSString in substring [duplicate] - ios

This question already has answers here:
NSString to NSArray
(7 answers)
Closed 8 years ago.
I want to split a string apple into substrings and want to store it in a array where I can get a at array[0] index p at array[1] and so on. Can anyone help me with that?

NSMutableArray *stringBuffer = [NSMutableArray arrayWithCapacity:[string length]];
for (int i = 0; i < [string length]; i++) {
[stringBuffer addObject:[NSString stringWithFormat:#"%C", [string characterAtIndex:i]]];
}
// doing stuff with the array

There are many ways to achieve this, few of them i am going to mention here:-
1)
NSMutableArray *yourArray = [NSMutableArray array];
for (int i = 0; i < [yourString length]; i++) {
[yourArray addObject:[NSString stringWithFormat:#"%C", [yourString characterAtIndex:i]]];
}
2) you can see this answer https://stackoverflow.com/a/3581549/1865424.
There are other ways too.

See: Convert NSString into char array
I don't know if the first of the 4 answers is the most efficient, but it works, is pretty clear in terms of how it's written and unless you've a particularly long string or high frequency of calls, is probably good enough.

You can use
const char* x = [String UTF8String];
then access characters like x[0] x[1] and so on.

Related

iOS - Displaying Two Words At A Time From String Array

I'm doing an RSVP reading project app where it blinks words on the screen. You can set the word chunk size (how many words you want displayed at a time) to either 1, 2, or 3. I got it working for 1 word by having my paragraph in a string and doing:
[self.textInput componentsSeparatedByString:#" ";
This makes me an array of words that I can use to blink one word at a time. How would I be able to do this with displaying 2 words at a time? Is there a way I can use this function again to do it differently, or should I iterate over this word array and make a new one with 2 word strings?
Any help or advice would be greatly appreciated as to what the best practice would to get this done. Thanks.
just like keith said create an array
NSArray *allwordsArray = [self.textInput componentsSeparatedByString:#" "];
Now you got all the info you need. Meaning you got the array with every word in it. Now its just a matter of putting it together. (I haven't tested this code)
NSMutableArray *twoWordArray = [[NSMutableArray alloc] init];
int counter=0;
for (int i=0; i<[allwordsArray count]; i++)
{
if (counter >= [allwordsArray count]) break;
NSString *str1 = [NSString stringwithformat#"%#", [allwordsArray objectAtIndex:counter]];
counter++;
if (counter >= [allwordsArray count]) break;
NSString *str2 = [NSString stringwithformat#"%#", [allwordsArray objectAtIndex:counter]];
NSString *combinedStr = [NSString stringwithformat#"%# %#", str1,str2];
[twoWordArray addObject: combinedStr];
counter++;
}
You have broken the string into components, which is on the right track. You could then make a smaller array that only includes components until you reach the chunk size. The final step would be to rejoin the string.
NSArray *components = [self.textInput componentsSeparatedByString:#" "];
NSRange chunkRange = NSMakeRange(0, chunkSize);
NSArray *lessComponents = [components subarrayWithRange:chunkRange];
NSString *newString = [lessComponents componentsJoinedByString:#" "];

Print symbols that were met in the text, no duplicates

I have been struggling with this question for couple days now. Really need your help and opinion.
We have a string, that holds a text:
NSString *contentOfFile = [[NSString alloc] initWithString:#"This is string#1"];
Now I have to log symbols, that were met in this string without duplicates. Result should look like this:
whitespace symbol here
#
1
g
h
i
n
r
s
t
I know that this is solved very simple in C code using char set and iterators but I am looking for the same simple and elegant way of handling this operation in objective-c.
I was thinking of using NSCharacterSet on the string somehow but I have a lack of knowledge in objective-c so I need your help guys please. Thanks in advance to everyone who replies.
Take advantage of a trait of NSSet: Its members are distinct.
NSString *contentOfFile = #"This is string#1";
NSMutableSet *set = [NSMutableSet set];
NSUInteger length = [contentOfFile length];
for (NSUInteger index = 0; index < length; index++)
{
NSString *substring = [contentOfFile substringWithRange:NSMakeRange(index, 1)];
[set addObject:substring];
}
NSLog(#"%#", set);
However, there's one remaining problem, and that is the members of a set are also unordered. Fortunately, arrays are ordered. So if you change the last line:
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:#"self" ascending:YES];
NSArray *array = [set sortedArrayUsingDescriptors:#[sortDescriptor]];
NSLog(#"%#", array);
If case insensitivity is important to you, there unfortunately is no 'case-insensitive' option for NSSet. However, you could convert your source string to all lowercase, like this:
NSString *contentOfFile = [#"This is string#1" lowercaseString];
and this would give you results exactly matching your sample output.
// Create the string
NSString *contentOfFile = #"This is string#1";
// Remove all whitespaces
NSString *whitespaceRemoval = [contentOfFile stringByReplacingOccurrencesOfString:#" " withString:#""];
// Initialize an array to store the characters
NSMutableArray *components = [NSMutableArray array];
// Iterate through the characters and add them to the array
for (int i = 0; i < [whitespaceRemoval length]; i++) {
NSString *character = [NSString stringWithFormat:#"%c", [whitespaceRemoval characterAtIndex:i]];
if (![components containsObject:character]) {
[components addObject:character];
}
}

componentsSeperatedByString returns full word [duplicate]

This question already has answers here:
Is there a simple way to split a NSString into an array of characters?
(4 answers)
Closed 9 years ago.
I am trying to get each letter of an NSString using this line of code:
NSArray *array = [string componentsSeparatedByString:#""];
//string is equal to Jake
NSLog(#"Array Count:%d",[array count]);
I am expecting to get each letter of the word "Jake" but instead I am getting the whole word. Why?
From Apple's Doc about this method
NSString *list = #"Norman, Stanley, Fletcher";
NSArray *listItems = [list componentsSeparatedByString:#", "];
produces an array { #"Norman", #"Stanley", #"Fletcher" }.
So empty separator will not separate each character of string, this
method doesn't work this way.
Here is an answer for your question
How to convert NSString to NSArray with characters one by one in Objective-C
The idea of separating a string by nothing doesn't logically make sense, it is like trying to divide by zero.
But to answer the question:
NSMutableArray *stringComponents = [NSMutableArray arrayWithCapacity:[string length]];
for (int i = 0; i < [string length]; i++) {
NSString *character = [NSString stringWithFormat:#"%c", [string characterAtIndex:i]];
[stringComponents addObject:character];
}`

How do I convert an array of ints to a NSString in Objective c?

First off, I'm pretty new to coding so bear with me if this is a dumb question.
I don't know how to convert soemthing like int array[10] into a single NSString.
I've been searching for solutions, but so far, all i've seen is converting from an array to an string array.
First thing I tried was something like
NSString *String=[NSString stringWithFormat #"%i",array];
But the thing is, i know that I can do something like
NSString *String[NSString stringWithFormat #"%i%i%i...",array[0],array[1],array[2],.....];
But i'm trying to avoid that since I will be doing this for more than 10 variables and I will be doing it quite a bit with seperately named variables
int i[] = {1,2,3,4,5,6,7};
int len = sizeof(i) / sizeof(int);
NSMutableString * str = [NSMutableString string];
for (int j = 0; j<len; j++) {
[str appendFormat:#"%i ", i[j]];
}
NSLog(#"%#",str);

Obj-c Turning long string into multidimensional array

I have a long NSString, something like "t00010000t00020000t00030000" and so on. I need to split that up into each "t0001000".
I'm using...
NSArray *tileData = [[GameP objectForKey:#"map"] componentsSeparatedByString:#"t"];
And it splits it up, but the "t" is missing, which I need (although I think I could append it back on). The other way I guess would be to split it up by counting 8 char's, although not sure how to do that.
But ideally I need it split into a [][] type array so I can get to each bit with something like...
NSString tile = [[tileData objectAtIndex:i] objectAtIndex:j]];
I'm new to obj-c so thanks for any help.
If they're not strictly the t characters that separate the sections, i. e. the parts are always 8 characters long, then it's very easy to do it:
NSString *string = #"t00010000t00020000t00030000";
NSMutableArray *arr = [NSMutableArray array];
int i;
for (i = 0; i < string.length; i += 8) {
[arr addObject:[string substringWithRange:NSMakeRange(i, 8)]];
}
and here arr will contain the 8-character substrings.
Edit: so let me also provide yet another solution for the multidimensional one. Of course #KevinH's solution with the characters is very elegant, but if you need an NSString and you don't mind implementing another method, it's fairly easy to add something like this:
#implementation NSString (EightCarAdditions)
- (NSString *)charAsStringInSection:(NSInteger)section index:(NSInteger)index
{
return [self substringWithRange:NSMakeRange(section * 8 + index, 1)];
}
- (unichar)charInSection:(NSInteger)section index:(NSInteger)index
{
return [self characterAtIndex:section * 8 + index];
}
#end
(Beware that characterAtIndex returns a unichar and not a char - be prepared for more than 1 byte-wide UTF-(8, 16, 32) stuff.) You can then call these methods on an NSString itself, so it's very convenient:
unichar ch = [string charInSection:1 index:3];
H2CO3's answer is spot-on for the first part. For the second (the multi-dimensional array), if I understand what you want, you don't need another array for the individual characters. For each NSString in the array, you can access each character by calling characterAtIndex. So, extending the example above:
for (NSString *item in arr) {
NSLog(#"The fifth character of this string is: %C", [item characterAtIndex:4]);
}
And if you're looking to chain these together, as in your example, you can do that too:
NSLog(#"The fifth character of the fourth string is: %C",
[[arr objectAtIndex:3] characterAtIndex:4]);

Resources