Make a replica of NSString - objective-c

I want to modify a NSString with reference to other string in Objective C, Can somebody help me.
Example1:
a. "ab cd eg"
b. "ctghml"
I want to change string b like "ct gh ml" , in short want to insert space spaces exactly like string a.
Note: Number of letters will be same like (abcdeg).count = 6 and (ctghml).count = 6
Example2:
a. (abcd) edt-tf
b. (lght)ert-tg
I want to change string b like "(lght) ert-tg" , in short want to insert space spaces exactly like string a.
Note: Number of letters will be same without spaces like ((abcd)edt-tf).count = 12 and ((lght)ert-tg).count = 12
Thanks!

NSString *str1 = #"ab cd eg";
NSMutableString *str2 = [#"ctghml" mutableCopy];
for(int i = 0; i < str1.length; i++) {
unichar c = [str1 characterAtIndex:i];
if (c == ' ') {
[str2 insertString:#" " atIndex:i];
}
}
NSLog(#"%#", str2);

Related

Concatenate integers and strings in Objective C

Please forgive the simplicity of the question. I'm completely new to Objective C.
I'd like to know how to concatenate integer and string values and print them to the console.
This is what I'd like for my output:
10 + 20 = 30
In Java I'd write this code to produce the needed results:
System.Out.Println(intVarWith10 + " + " + intVarWith20 + " = " + result);
Objective-C is quite different. How can we concatenate the 3 integers along with the strings in between?
You can use following code
int iFirst,iSecond;
iFirst=10;
iSecond=20;
NSLog(#"%#",[NSString stringWithFormat:#"%d + %d =%d",iFirst,iSecond,(iFirst+iSecond)]);
Take a look at NSString - it has a method stringWithFormat that does what you require. For example:
NSString* yString = [NSString stringWithFormat:#"%d + %d = %d",
intVarWith10, intVarWith20 , result];
You can use C style syntax, with NSLog (If you just need to print)
NSLog(#"%d+%d=%d",intvarWith10,intvarWith20,result);
If you want a string variable holding the value
NSString *str = [NSString stringWithFormat:#"%d+%d=%d",intvarWith10,intvarWith20,result];
You have to create an NSString with format and specify the data type.
Something like this :
NSInteger firstOperand=10;
NSInteger secondOperand=20;
NSInteger result=firstOperand+secondOperand;
NSString *operationString=[NSString stringWithFormat:#"%d + %d = %d",firstOperand,secondOperand,result];
NSLog(#"%#",operationString);
NSString with format follows the C printf syntax
Check below code :
int i = 8;
NSString * tempStr = [NSString stringWithFormat#"Hello %d",i];
NSLog(#"%#",tempStr);
I strongly recommend you this link Objective-C Reference.
The Objective-C int data type can store a positive or negative whole number. The actual size or range of integer that can be handled by the int data type is machine and compiler implementation dependent.
So you can store like this.
int a,b;
a= 10;
b= 10;
then performing operation you need to first understand NSString.
C style character strings are composed of single byte characters and therefore limited in the range of characters that can be stored.
int C = a + b;
NSString *strAnswer = [NSString stringWithFormat:#"Answer %d + %d = %d", a , b, c];
NSLog(#"%#",strAnswer)
Hope this will help you.

In Objective-C, how to print out N spaces? (using stringWithCharacters)

The following is tried to print out N number of spaces (or 12 in the example):
NSLog(#"hello%#world", [NSString stringWithCharacters:" " length:12]);
const unichar arrayChars[] = {' '};
NSLog(#"hello%#world", [NSString stringWithCharacters:arrayChars length:12]);
const unichar oneChar = ' ';
NSLog(#"hello%#world", [NSString stringWithCharacters:&oneChar length:12]);
But they all print out weird things such as hello ÔÅÓñüÔÅ®Óñü®ÓüÅ®ÓñüÔ®ÓüÔÅ®world... I thought a "char array" is the same as a "string" and the same as a "pointer to a character"? The API spec says it is to be a "C array of Unicode characters" (by Unicode, is it UTF8? if it is, then it should be compatible with ASCII)... How to make it work and why those 3 ways won't work?
You can use %*s to specify the width.
NSLog(#"Hello%*sWorld", 12, "");
Reference:
A field width, or precision, or both, may be indicated by an asterisk
( '*' ). In this case an argument of type int supplies the field width
or precision. Applications shall ensure that arguments specifying
field width, or precision, or both appear in that order before the
argument, if any, to be converted.
This will get you what you want:
NSLog(#"hello%#world", [#"" stringByPaddingToLength:12 withString:#" " startingAtIndex:0]);
I think the issue you have is you are misinterpreting what +(NSString *)stringWithCharacters:length: is supposed to do. It's not supposed to repeat the characters, but instead copy them from the array into a string.
So in your case you only have a single ' ' in the array, meaning the other 11 characters will be taken from whatever follows arrayChars in memory.
If you want to print out a pattern of n spaces, the easiest way to do that would be to use -(NSString *)stringByPaddingToLength:withString:startingAtIndex:, i.e creating something like this.
NSString *formatString = #"Hello%#World";
NSString *paddingString = [[NSString string] stringByPaddingToLength: n withString: #" " startingAtIndex: 0];
NSLog(formatString, paddingString);
This is probably the fastest method:
NSString *spacesWithLength(int nSpaces)
{
char UTF8Arr[nSpaces + 1];
memset(UTF8Arr, ' ', nSpaces * sizeof(*UTF8Arr));
UTF8Arr[nSpaces] = '\0';
return [NSString stringWithUTF8String:UTF8Arr];
}
The reason your current code isn't working is because +stringWithCharacters: expects an array with a length of characters of 12, while your array is only 1 character in length {' '}. So, to fix, you must create a buffer for your array (in this case, we use a char array, not a unichar, because we can easily memset a char array, but not a unichar array).
The method I provided above is probably the fastest that is possible with a dynamic length. If you are willing to use GCC extensions, and you have a fixed size array of spaces you need, you can do this:
NSString *spacesWithLength7()
{
unichar characters[] = { [0 ... 7] = ' ' };
return [NSString stringWithCharacters:characters length:7];
}
Unfortunately, that extension doesn't work with variables, so it must be a constant.
Through the magic of GCC extensions and preprocessor macros, I give you.... THE REPEATENATOR! Simply pass in a string (or a char), and it will do the rest! Buy now, costs you only $19.95, operators are standing by! (Based on the idea suggested by #JeremyL)
// step 1: determine if char is a char or string, or NSString.
// step 2: repeat that char or string
// step 3: return that as a NSString
#define repeat(inp, cnt) __rep_func__(#encode(typeof(inp)), inp, cnt)
// arg list: (int siz, int / char *input, int n)
static inline NSString *__rep_func__(char *typ, ...)
{
const char *str = NULL;
int n;
{
va_list args;
va_start(args, typ);
if (typ[0] == 'i')
str = (const char []) { va_arg(args, int), '\0' };
else if (typ[0] == '#')
str = [va_arg(args, id) UTF8String];
else
str = va_arg(args, const char *);
n = va_arg(args, int);
va_end(args);
}
int len = strlen(str);
char outbuf[(len * n) + 1];
// now copy the content
for (int i = 0; i < n; i++) {
for (int j = 0; j < len; j++) {
outbuf[(i * len) + j] = str[j];
}
}
outbuf[(len * n)] = '\0';
return [NSString stringWithUTF8String:outbuf];
}
The stringWithCharaters:length: method makes an NSString (or an instance of a subclass of NSString) using the first length characters in the C array. It does not iterate over the given array of characters until it reaches the length.
The output you are seeing is the area of memory 12 Unicode characters long starting at the location of your passed 1 Unicode character array.
This should work.
NSLog(#"hello%#world", [NSString stringWithCharacters:" " length:12]);

How can get sequence match count in NSString objects by using NSCharacterset class?

Always i have a mind thanks for your help..
I'm trying to count sequence matchs NSString objects by using NSCharacterset class.
It seems difficult question...
NSString *StringFirst = #"ABCDEFGHI"; <= Sequence characters.
NSString *StringSecond = #"DGHIJ";
// StringSecond object compare sequence in StringFirst object.
// result is following.
result : 2 (Because StringSecond object D -> G sequence no matching in StringFirst,
G -> H matches, so count : 1
H -> I matches, so count : 2
I -> J no matches so count : 2)
Gentleman, Please help..
I don't know why you want to accomplish this using NSCharacterset class and I presume there is no way to do that since NSCharacterset handles individual characters, since in your case a string is to be checked. Here is an alternative, hope it may help.
NSString *StringFirst = #"ABCDEFGHI";
NSString *StringSecond = #"DGHIJ";
int count = 0;
for (int i=0; i< [StringSecond length]; i++) {
if (i+2 <= [StringSecond length]) {
NSString *subStringFromSecond = [StringSecond substringWithRange:NSMakeRange(i, 2)];
NSRange range = [StringFirst rangeOfString:subStringFromSecond];
if (range.length) {
count++;
}
}
}
// count gives matched count,

How do I break a text string down to two letter chunks, and convert those chunks to four digit numbers in Objective-C?

I want to make a simple program for my number theory class. We're learning encryption.
The main encryption I want to demonstrate is demonstrated in this example:
Take the phrase "TAKE CARE"
as
TA
KE
-C
AR
E-
where TA is converted to 2001, because T is the 20th letter in the alphabet and A is the first.
Well, since you seem to be limiting yourself to ASCII, then you should be fine using the -UTF8String of the string:
NSString *source = #"TAKE CARE";
source = [source lowercaseString]; //normalize the capitalization
const char *characters = [source UTF8String];
for (NSUInteger i = 0; i < [source length]; ++i) {
const char character = characters[i];
if (character >= 'a' && character <= 'z') {
int positionInAlphabet = character - 'a' + 1; // this means "a" is "1"
NSLog(#"%c = %d", character, positionInAlphabet);
} else {
NSLog(#"non-letter: %c", character);
}
}

How to add an integer into String using objective c?

I am a java programmer, I found that Java is very good at doing string.
If I want to do this objective c, how can I do in objective c ?
System.out.println("This is a " + 123 + " test");
To place an integer into a string, you can do this:
int n = 123;
NSString *s = [NSString stringWithFormat:#"This is a %d test", n];
There are numerous other ways. But concatenating strings with integers by + operator is not one of them. :)
To place an integer into a string, you can do this:
int number = 123;
NSString *string = [NSString stringWithFormat:#"This is a %i test", number];
Or if you want to NSLog you have to do this :
int number = 123;
NSLog(#"This is a %i test", number);
It is very EASY !!!