This works fine, we all know that:
NSString *textoutput = #"Hello";
outLabel.text = textoutput;
However, what if you want to include a variable inside that NSString statement like the following:
NSString *textoutput =#"Hello" Variable;
In C++ I know when I cout something and I wanted to include a variable all I did was soemthing like this:
cout << "Hello" << variableName << endl;
So I'm trying to accomplish that with Objective-C but I don't see how.
You can do some fancy formatting using the following function:
NSString *textoutput = [NSString stringWithFormat:#"Hello %#", variable];
Note that %# assumes that variable is an Objective-C object. If it's a C string, use %s, and if it's any other C type, check out the printf reference.
Alternatively, you can create a new string by appending a string to an existing string:
NSString *hello = #"Hello";
NSString *whatever = [hello stringByAppendingString:#", world!"];
Note that NSString is immutable -- once you assign a value, you can't change it, only derive new objects. If you are going to be appending a lot to a string, you should probably use NSMutableString instead.
I have The Cure you're looking for, Robert Smith:
if your variable is an object, use this:
NSString *textOutput = [NSString stringWithFormat:#"Hello %#", Variable];
The '%#' will only work for objects. For integers, it's '%i'.
For other types, or if you want more specificity over the string it produces, use this guide
Related
I understand pointers work with addresses and not the data itself. This is why I need to use the address-of (&) operator below as I need to assign the address of num to the pointer and not the actual value of num (40).
int num = 40;
int *numPtr = #
Therefore i'm confused as to why I can do this.
NSString *str = #"hello";
I've created a pointer str but instead of giving it an address i'm able to assign it some data, a literal string.
I thought pointers could only hold memory addresses so why am I able to directly assign it some data?
For someone trying to get their head around pointers and objects this is very confusing.
No you are not assigning a literal string to it, # makes a NSString object with the string value hello.
In most C languages strings are just an array of char, where char is a primitive type like int like in your example.
There is a reason you put an # before string literals (when you want an NSString and not a C string) in objective-c
#"String" is basically equivalent to [NSString stringWithCString:"string"] which returns a pointer to an NSString object containing the value "string"
It is the same way 1 is a c type integer, but #1 is a NSNumber representing the value of 1. If you see an # it means "this is shorthand for creating an object". (#[] for NSArrays, #{} for NSDictionarys, #(), #123, #YES, #NO for NSNumbers, and #"" for NSString)
C does not have strings. Usually char arrays are used to represent them.
NSString *str = #"hello";
can be thought of as short hand (literal) for:
char charArray[] = "hello";
NSString *str = [[NSString alloc] initWithBytes:charArray length:sizeof(charArray) encoding:NSUTF8StringEncoding]; // disregard character encoding for this example
or
unichar bla[] = {'h', 'e', 'l', 'l', 'o'};
str = [[NSString alloc] initWithCharacters:bla length:sizeof(bla)];
So an object is created and thus you need a pointer.
I want a input from user their name and output that input name in NSLog using NSString.
I don't know which % sign and how to output that.
Can i use scanf() function for that?
Please help me , i am just beginner of Objective-C.
You can use %# for all objects including NSString. This will in turn call the objects description method and print the appropriate string. Most objects have a rather useful representation already there (e.g. NSArray objects return the descriptions of all their contents).
Mark Dylan is the name which would be stored in the Name variable.
NSString* Name = #"Mark Dylan";
This code will allow you to ask their name and scan it into memory which will be stored in the Name variable.
NSLog(#"What is your name?");
scanf("%#", &Name);
If you want to print out the variable you can use;
NSLog(#"Your name is %#", Name);
%# is what you want. It fit for object like NSString, [YourViewController class]
To get input from the user use a UITextField or a NSTextField. To output a string to the log file you can use NSLog, ie:
NSString* userName = #"Zawmin";
NSLog(#"name = %#", userName);
NSLog accepts a format string, so you can do something like this:
#include <stdio.h>
#include <Foundation/Foundation.h>
// 1024 characters should be enough for a name.
// If you want something more flexible, you can use GNU readline:
// <http://cnswww.cns.cwru.edu/php/chet/readline/rltop.html>
#define MAX_NAME_LENGTH 1024
// Get name from user input
char name[MAX_NAME_LENGTH];
name[0] = '\0'; // just in case fgets fails
fgets(name, MAX_NAME_LENGTH, stdin);
// Put name into NSString object and output it.
NSString *name = [NSString stringWithUTF8String:name];
NSLog(#"%#", name);
%# works for all Objective-C objects.
If you want to output a C-string (char* or const char*), use %s. Never put a non-literal string as the first argument to NSLog as this opens security holes.
NSString *string = #"HELLO";
For some reason, XCode won't auto-complete methods like remove characters or append etc... If that's the case, how can I, say, remove certain characters from my string? Say I want to remove all the L's.
NSString doesn't respond to those methods. NSMutableString does, but you've declared an immutable string variable and assigned to it a string literal. Since an Objective-C #"string literal" is always immutable (an instance of NSString but not NSMutableString), there's no way those messages can be sent to the object you're using.
If you want a mutable string, try:
NSMutableString *mutableString = [[#"HELLO" mutableCopy] autorelease];
That's an immutable string literal.
Here is a great post explaining it in further details:
What's the difference between a string constant and a string literal?
As for your question on how would you change it and remove the Ls:
NSString *hello = #"HELLO";
NSString *subString = [hello stringByReplacingOccurrencesOfString:#"L" withString:#""];
NSLog(#"subString: %#", subString);
That outputs "HEO"
Either that or you can create an NSMutableString by creating a copy of the mutable string like Jonathan mentioned. In both examples, you're copying it into a non-literal string.
I have a constant defined as:
#define BEGIN_IMPORT_STRING #"Importing Hands!";
But I get an error when I try to concat with:
NSString *updateStr = [NSString stringWithFormat:#"%#%#", BEGIN_IMPORT_STRING, #" - Reading "];
This doesn't happen if I replace it with a string literal
NSString *updateStr = [NSString stringWithFormat:#"%#%#", #"foo", #" - Reading "];
Or a local string
NSString *temp = #"foo";
NSString *updateStr = [NSString stringWithFormat:#"%#%#", temp, #" - Reading "];
You need to remove the semicolon from your #define:
#define BEGIN_IMPORT_STRING #"Importing Hands!"
To the compiler, the resulting line looks like this:
NSString *updateStr = [NSString stringWithFormat:#"Importing Hands!";, #" - Reading "];
Replace
#define BEGIN_IMPORT_STRING #"Importing Hands!";
with
#define BEGIN_IMPORT_STRING #"Importing Hands!"
This is because compiler in your case replaces all occurrences of BEGIN_IMPORT_STRING with #"Importing Hands!";
Aside from the accepted answer (remove semicolon), note that:
#"Foo" is an NSString. You can even send it a message.
#define FOO #"Foo" is a preprocessor macro, not a constant. It's a typing shortcut.
Though macros aren't an uncommon way to avoid retyping the same string, they're an unfortunate holdover. Essentially, they're playing games that aren't necessary anymore.
For repeated strings, I prefer:
static NSString *const Foo = #"Foo;
The const portion of this definition ensures that the pointer is locked down, so that Foo can't be made to point to a different object.
The static portion restricts the scope to the file. If you want to access it from other files, remove the static and add the following declaration to your header file:
extern NSString *const Foo;
Should you be using
NSLocalizedString(#"Importing Hands!", #"Message shown when importing of hands starts");
?
I put it as an answer because this looks like something you would not want to have to go and redo through all your code.
Is there a general purpose function in Objective-C that I can plug into my project to simplify concatenating NSStrings and ints?
[NSString stringWithFormat:#"THIS IS A STRING WITH AN INT: %d", myInt];
That's typically how I do it.
Both answers are correct. If you want to concatenate multiple strings and integers use NSMutableString's appendFormat.
NSMutableString* aString = [NSMutableString stringWithFormat:#"String with one int %d", myInt]; // does not need to be released. Needs to be retained if you need to keep use it after the current function.
[aString appendFormat:#"... now has another int: %d", myInt];
NSString *s =
[
[NSString alloc]
initWithFormat:#"Concatenate an int %d with a string %#",
12, #"My Concatenated String"
];
I know you're probably looking for a shorter answer, but this is what I would use.
string1,x , these are declared as a string object and integer variable respectively. and if you want to combine both the values and to append int values to a string object and to assign the result to a new string then do as follows.
NSString *string1=#"Hello";
int x=10;
NSString *string2=[string1 stringByAppendingFormat:#"%d ",x];
NSLog(#"string2 is %#",string2);
//NSLog(#"string2 is %#",string2); is used to check the string2 value at console ;
It seems the real answer is no - there is no easy and short way to concatenate NSStrings with Objective C - nothing similar to using the '+' operator in C# and Java.