replace characters in NSString - objective-c

I would like to wipe a NSString object in my code (replace every characters by 0).
To do that I tried this :
NSString *myString;
for (int i=0; i<[myString length]; i++)
{
myString[i] = 0;
}
But it doesn't compile : "Incompatible types in assignment" at line myString[i] = 0;
I understand, but I can't use function stringByReplacingOccurancesOfString because it creates a new object and I would like to replace characters in my first object.
Any help ?

NSString is immutable, meaning that you can not change its contents once its created. You have NSMutableString for that purpose.
Also, you can not access the characters in a NSString or NSMutableString with this syntax:
myString[i] = 0;
NSStrings and NSMutableStrings are objects and you work with objects by sending messages to them. For instance, you have characterAtIndex: method that returns the character at the given index, or NSMutableString's replaceOccurrencesOfString:withString:options:range: that replaces all occurrences of a given string in a given range with another given string.

By Definition, NSString is an immutable class, so the data inside of it is unchangeable.
You are looking for the NSMutableString class, which implements the following method:
replaceOccurrencesOfString:withString:options:range:
Which you can use to replace characters or substrings within the object you send that message to.

Related

How to replace a char in an an char array? Xcode

i got the following char array in Objective-C (Xcode):
char *incomeMessage;
NSString *str = [[NSString alloc] initWithBytes:data.bytes length:data.length encoding:NSUTF8StringEncoding];
incomeMessage = [str UTF8String];
NSLog(#"%c", incomeMessage[0]);
NSLog(#"%c", incomeMessage[1]);
NSLog(#"%c", incomeMessage[2]);
NSLog(#"%c", incomeMessage[3]);
NSLog(#"%c", incomeMessage[4]);
NSLog(#"%c", incomeMessage[5]);
For example I get some results like this in console:
"3
2
6
1
8
4"
Now i want to replace the char in incomeMessage[2] by 4:
incomeMessage[2] = '4';
But then it gives me the error:
EXC_BAD_ACCESS
Do you have an idea, how to solve the problem?
According to the reference documentation, UTF8String returns a read-only (const char*) reference to the string data.
The reference material goes on to note:
This C string is a pointer to a structure inside the string object,
which may have a lifetime shorter than the string object and will
certainly not have a longer lifetime. Therefore, you should copy the C
string if it needs to be stored outside of the memory context in which
you use this property.
So I'd suggest following their advice and creating a copy of the array and then performing your modifications against that.
For example: http://ideone.com/mhjwZW
You might have better luck with something like:
NSString* str = [[NSString alloc] initWithBytes:data.bytes length:data.length encoding:NSUTF8StringEncoding];
char* incomeMessage = malloc([str lengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
strcpy(incomeMessage, [str UTF8String]);
//now you can change things
incomeMessage[2] = '4';
//do this when you're done
free(incomeMessage);
Although, is there any particular reason why you want to use a C-string/character array as opposed to an NSMutableString? I think you might find replaceCharactersInRange:withString: a better approach generally. See also: stringByReplacingCharactersInRange:withString:.
i got the following char array in Objective-C (Xcode)
You don't, you know. All you have is a pointer. You have not set aside any actual memory; there is no array there.
incomeMessage = [str UTF8String];
All you've done in that line is repoint the pointer incomeMessage at your string's UTF8String. A string's UTF8String is immutable. Note this passage in the docs:
you should copy the C string if it needs to be stored outside of the memory context in which you use this property.
So basically, if you want to write into an array of char, your first task should be to make an array of char.

NSString (or NSArray or something) to variable parameter list of C (char *) strings

Is there any easy way to convert an Objective-C holding class of NSStrings into parameters for a function accepting a variable list of char *? Specifically I have a function like:
-(void)someFunction:(NSSomething *) var
that I want to forward to a C function like
void someCFunction(char * var, ...)
Is there an easy way to go about this?
No, you can only do what you want if the number of arguments you're passing is known at compile time. If you just want to convert a single string, use the -UTF8String message:
// Example with two strings
NSString *str1 = ...;
NSString *str2 = ...;
someCFunction([str1 UTF8String], [str2 UTF8String]); // etc.
But if the number of strings will vary at runtime, you'll need to use a different API, if one is available. For example, if there's an API that took an array of strings, you could convert the Objective-C array into a C array:
// This function takes a variable number of strings. Note: in C/Objective-C
// (but not in C++/Objective-C++), it's not legal to convert 'char **' to
// 'char *const *', so you may sometimes need a cast to call this function
void someCFunction(const char *const *stringArray, int numStrings)
{
...
}
...
// Convert Objective-C array to C array
NSArray *objCArray = ...;
int numStrings = [objCArray count];
char **cStrArray = malloc(numStrings * sizeof(char*));
for (int i = 0; i < count; i++)
cStrArray[i] = [[objCArray objectAtIndex:i] UTF8String];
// Call the function; see comment above for note on cast
someCFunction((const char *const *)cStrArray, numStrings);
// Don't leak memory
free(cStrArray);
This would do the trick:
NSString *string = #"testing string"
const char * p1=[string UTF8String];
char * p2;
p2 = const_cast<char *>(p1);
Yes, this can be done, and is explained here:
How to create a NSString from a format string like #"xxx=%#, yyy=%#" and a NSArray of objects?
And here:
http://www.cocoawithlove.com/2009/05/variable-argument-lists-in-cocoa.html
With modifications for ARC here:
How to create a NSString from a format string like #"xxx=%#, yyy=%#" and a NSArray of objects?
Also, variable arguments are not statically or strongly typed, as the other poster seems to be suggesting. In fact, there is no clear indication in the callee of how many arguments you really have. Determining the number of arguments generally breaks down into having to either specify the number by an count parameter, using a null terminator, or inferring it from a format string a la (s)print* . This is frankly why the C (s)print* family of functions has been the source of many errors, now made much much safer by the XCode / Clang / GCC compiler that now warns.
As an aside, you can approach statically typed variable arguments in C++ by creating a template method that accepts an array of an unspecified size. This is generally considered bad form though as the compiler generates separate instances for each size of array seen by by the compiler (template bloat).

Random uppercase - lowercase

I'd like to let a string change letters to lowercase or uppercase randomly(in Xcode).
for example: "example" to "ExaMpLe" or "eXAMPle" or ExAmPlE" or something else like this randomly..
hot can i solve this?
thanks
You could either use the -uppercaseString and -lowercaseString methods on substrings, or use the toupper() and tolower() functions on characters. There's no way to simply filter a string; you'll want to use either an NSMutableString or a C array of characters.
See this question for how to get a random boolean value, which you can use to decide whether a character should be uppercase or lowercase.
NSString has both a lowercaseString and uppercaseString method. You can iterate over the characters in a string as a sequence of substrings, using some random source to call the appropriate lower/upper case on each of them, collecting the result. Something like...
NSMutableString result = [NSMutableString string];
for (NSUInteger i = 0; i < [myString length]; i++)
{
NSString *substring = [myString substringWithRange:NSMakeRange(i, 1)];
[result appendString:(rand() % 2) ? [substring lowercaseString]
: [substring uppercaseString]];
}
You may prefer a better source of entropy than rand, but it'll do for an example (don't forget to seed it if you use this case as is). If the strings are large, you can do it in-place on an NSMutableString.
You could break the word into an array of letters, and loop over this using a random number to determining case, after looping the array, simply stick the letters back together using NSMutableString.
NSString had a uppercaseString and lowercaseString methods you can use.

Append char to an existing string Objective - C

I'm trying to append and programmatically modify a NSString on the fly. I'd like to know a couple of things:
How do I modify specific chars in a defined NSString?
How do I add chars in a defined NSString?
For example if I have the following defined: NSString *word = [[NSString alloc] initWithString:#"Hello"]; how would I be able to replace the letter "e" with "a" and also how would I add another char to the string itself?
Nerver use NSString for string manipulation,Use NSMutableString.
NSMutableString is the subclass of NSString and used for that purpose.
From Apple Documentation:
The NSString class declares the programmatic interface for an object that manages immutable strings. (An immutable string is a text string that is defined when it is created and subsequently cannot be changed. NSString is implemented to represent an array of Unicode characters (in other words, a text string).
The mutable subclass of NSString is NSMutableString.
NSMutableString *word = [[NSMutableString alloc] initWithString:#"Hello"];
//Replace a character
NSString* word2 = [word stringByReplacingOccurrencesOfString:#"e" withString:#"a"];
[word release];
word = nil ;
word = [[NSMutableString alloc] initWithString:word2 ];
//Append a Character
[word appendString:#"a"];
There are more string manipulating function See Apple Documentation for NSMutableString
Edited:
you could first use rangeOfString to get the range of the string (in your case #"e").
- (NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask
then check the NSRange object if it's valid then use the replaceCharactersInRange function on your NSMutableString to replace the set of characters with your string.
- (void)replaceCharactersInRange:(NSRange)aRange withString:(NSString *)aString
NSString instances are immutable. You can create new NSString instances by appending or replacing characters in another like this:
NSString *foo = #"Foo";
NSString *bar = #"Bar";
NSString *foobar = [foo stringByAppendingString:bar];
NSString *baz = [bar stringByReplacingOccurrencesOfString:#"r" withString:#"z"];
If you really need to modify an instance directly, you can use an NSMutableString instead of an NSString.
If you really want to use primitive characters, NSString has a couple of initializers that can take character arrays (e.g. initWithCharacters:length:).
First things first:
If you are going to modify an string, you have to use NSMutableString. NSStrings can't be modified, hence they have a modifiable companion.
Then, NSMutableString has two methods that you are going to find helpful:
replaceCharactersInRange:withString
deleteCharactersInRange:
(Sorry for not linking directly to those method's links. StackOverflow if always imposing limitations to me as a new user...).
Just to add, NSMutableString has a method called appendFormat, which can be of great help when appending stuff:
[str appendFormat:#"%#-%#-%#", #"1", #"2",#"3"]
will append "1-2-3" to to str

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);