Shortest code to create a string with specified lengh - objective-c

What is the shortest way to create a string with spaces and desired length in Objective-C?
I can do it using for cycle, but it's several lines of code.

Returns first six characters
NSString *fullName = #"Warif Akhand Rishi";
NSString *subString = [fullName substringToIndex:6];

Have you looked at stringWithFormat ?
[NSMutableString stringWithFormat:#"%20d", 42];

Related

How to break a NSString into words with non-significant blank suppression?

I have several NSStrings with a format similar to the one below:
"Hello, how are you?"
How can I break the string into an array of words? For example, for the above sentence I would expect an array consisting of "Hello,", "how", "are", "you?"
Usually I would break the string into words by using the function [NSString componentsSeparatedByCharactersInSet: NSCharacterSet set]
However this won't work in this situation because the spaces between the words are of unequal length. Note I will not be aware of the size of each word and the space between them.
How can I accomplish this? I am working on an app for OSX not iOS.
EDIT: My eventual goal is to retrieve the second word in the sentence. If there is a easier way to do this without breaking the string into an array please feel free to suggest it.
Try this:
NSMutableArray *parts = [NSMutableArray arrayWithArray:[str componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]];
[parts removeObjectIdenticalTo:#""];
NSString *res = [parts objectAtIndex:1]; // The second string
Well, you could actually write a loop to iterate through the characters and find the first non-blank after the first blank, then iterate further to find the ending blank (or end of line). Would probably be about 5x faster (with much fewer object allocations) than using one of the other methods, and could be done in about 10 lines.
If you dont want to use a CharacterSet try this to remove extra spaces:
NSString* string = #"word1, word2 word3 word4";
bool done = false;
do {
NSString tempStr = [string stringByReplacingOccurrencesOfString:#" " withString:#" "];
done = [string isEqualToString:tempStr];
string = tempStr;
} while (!done);
NSLog(#"%#", string);
this will output "word1, word2 word3 word4"

How to omit a certain substring out of an NSString?

I would like to know how it is possible to omit a specific substring out an NSString, assuming the NSString does contain that substring.
For example:
Original string: "This is a string but these words should be omitted."
Substring to omit: "but these words should be omitted".
Result string: "This is a string."
Thanks ahead,
iLyrical.
NSString *originalString = #"This is a string but these words should be omitted.";
NSString *substringToOmit = #" but these words should be omitted";
NSString *resultString = [originalString stringByReplacingOccurencesOfString:substringToOmit
withString:#""];
See NSString's stringByReplacingOccurrencesOfString:withString:. You may also want to trim the trailing whitespace with stringByTrimmingCharactersInSet:.

\n does not skip to next line in NSString

NSMutableString *a = #"Hi";
NSMutableString *b =[a stringByAppendingString:#"\n\n Hi Again"];
The above doesn't give an error but does not put "Hi Again" on the next line. Why?
EDIT2
I realised after posting, that the OP had NSString in the title but put NSMutableString in the code. I have submitted an edit to change the NSMutableString to NSString.
I will leave this as it still maybe helpful.
Well I am surprised that does not give an error, because you are giving a NSMutableString a NSString.
You need to read the Documentation on NSMutableStrings.
to give you an idea
//non mutable strings
NSString *shortGreetingString = #"Hi";
NSString *longGreetingString = #"Hi Again";
/*mutable string - is created and given a character capacity The number of characters indicated by capacity is simply a hint to increase the efficiency of data storage. The value does not limit the length of the string
*/
NSMutableString *mutableString= [NSMutableString stringWithCapacity:15];
/*The mutableString, now uses an appendFormat to construct the string
each %# in the Parameters for the appendFormat is a place holder for values of NSStrings
listed in the order you want after the comma.
Any other charactars will be included in the construction, in this case the new lines.
*/
[mutableString appendFormat:#"%#\n\n%#",shortGreetingString,longGreetingString];
NSLog (#"mutableString = %#" ,mutableString);
[pool drain];
I think this might help you. You'd rather to use '\r' instead of '\n'
I also had a similar problem and found \n works in LLDB but not in GDB
Try using NSString. You could use:
NSString *a = [NSString stringWithFormat:#"%#\n\n%#", #"Hi", #"Hello again"]
If your string is going in a UIView (e.g a UILabel), you also need to set the number of lines to 0
myView.numberOfLines=0;

Replacing one character in a string in Objective-C

Hoping somebody can help me out - I would like to replace a certain character in a string and am wondering what is the best way to do this?
I know the location of the character, so for example, if I want to change the 3rd character in a string from A to B - how would I code that?
If it is always the same character you can use:
stringByReplacingOccurrencesOfString:withString:
If it is the same string in the same location you can use:
stringByReplacingOccurrencesOfString:withString:options:range:
If is just a specific location you can use:
stringByReplacingCharactersInRange:withString:
Documentation here:
https://developer.apple.com/documentation/foundation/nsstring
So for example:
NSString *someText = #"Goat";
NSRange range = NSMakeRange(0,1);
NSString *newText = [someText stringByReplacingCharactersInRange:range withString:#"B"];
newText would equal "Boat"
NSString *str = #"123*abc";
str = [str stringByReplacingOccurrencesOfString:#"*" withString:#""];
//str now 123abc
Here is the code:
[aString stringByReplacingCharactersInRange:NSMakeRange(3,1) withString:#"B"];
Use the replaceCharactersInRange: withString: message on a NSMutableString object.

How to get a single NSString character from an NSString

I want to get a character from somewhere inside an NSString. I want the result to be an NSString.
This is the code I use to get a single character at index it:
[[s substringToIndex:i] substringToIndex:1]
Is there a better way to do it?
This will also retrieve a character at index i as an NSString, and you're only using an NSRange struct rather than an extra NSString.
NSString * newString = [s substringWithRange:NSMakeRange(i, 1)];
If you just want to get one character from an a NSString, you can try this.
- (unichar)characterAtIndex:(NSUInteger)index;
Used like so:
NSString *originalString = #"hello";
int index = 2;
NSString *theCharacter = [NSString stringWithFormat:#"%c", [originalString characterAtIndex:index-1]];
//returns "e".
Your suggestion only works for simple characters like ASCII. NSStrings store unicode and if your character is several unichars long then you could end up with gibberish. Use
- (NSRange)rangeOfComposedCharacterSequenceAtIndex:(NSUInteger)index;
if you want to determine how many unichars your character is. I use this to step through my strings to determine where the character borders occur.
Being fully unicode able is a bit of work but depends on what languages you use. I see a lot of asian text so most characters spill over from one space and so it's work that I need to do.
NSMutableString *myString=[NSMutableString stringWithFormat:#"Malayalam"];
NSMutableString *revString=#"";
for (int i=0; i<myString.length; i++) {
revString=[NSMutableString stringWithFormat:#"%c%#",[myString characterAtIndex:i],revString];
}
NSLog(#"%#",revString);