Make a string encoder in objective-C - objective-c

I am a beginner of learning how to code and I want to write a string coder. By string coder, I mean if we input the word "abc", the output is "cde". That is, every character move to plus 2.
I'm able to convert a single character, for example: input "a" -> output "c".
But I'm not sure how to input a word instead of a character.
char passWord[40];
NSLog(#" Plz enter the password");
scanf("%s",passWord);
NSString *tempCode = [NSString stringWithCString:passWord encoding:1];
//NSLog(#"test %#", tempCode);
int decode, asciiCode = [tempCode characterAtIndex:0];
//NSLog(#"test %d", asciiCode);
decode = asciiCode + 2;
NSString *decodeNum = [NSString stringWithFormat:#"%c", decode];
NSLog(#"%#", decodeNum);

Related

Conversion from NSString to Hex

i am new in this field and i was working on a conversion of NSString to Hex and have been stuck into it. My String lets suppose is 1,FF,F8 now how can i convert that into hex numbers like 0x01,0x0FF and 0x0F8
First step would be to split the string containing "1,FF,F8" into three strings containing the separate hex values, "1", "FF", "F8".
NSString *hexString = #"1,FF,F8";
NSArray *hexValues = [hexString componentsSeparatedByString:#","];
As for the conversion from NSString to hex, I'm not quite sure what exactly you want.
If you just want to add on a "0x0" to the beginning of the hex values, you can just do:
NSMutableArray *formattedHexValues = [NSMutableArray array];
for(NSString *hexValue in hexValues) {
[formattedHexValues addObject:[NSString stringWithFormat:#"0x0%#", hexValue]];
}
If you want to actually get the integer value of the hex string, do this:
for(NSString *hexString in formattedHexValues) {
unsigned int value;
[[NSScanner scannerWithString:hexString] scanHexInt:&value];
NSLog(#"The value is %d", value);
}
Typed this out in the browser so there might be a syntax mistake or two, but it generally should work fine.

How to read input in Objective-C?

I am trying to write some simple code that searches two dictionaries for a string and prints to the console if the string appears in both dictionaries. I want the user to be able to input the string via the console, and then pass the string as a variable into a message. I was wondering how I could go about getting a string from the console and using it as the argument in the following method call.
[x rangeOfString:"the string goes here" options:NSCaseInsensitiveSearch];
I am unsure as to how to get the string from the user. Do I use scanf(), or fgets(), into a char and then convert it into a NSSstring, or simply scan into an NSString itself. I am then wondering how to pass that string as an argument. Please help:
Here is the code I have so far. I know it is not succinct, but I just want to get the job done:
#import <Foundation/Foundation.h>
#include <stdio.h>
#include "stdlib.h"
int main(int argc, const char* argv[]){
#autoreleasepool {
char *name[100];
printf("Please enter the name you wish to search for");
scanf("%s", *name);
NSString *name2 = [NSString stringWithFormat:#"%s" , *name];
NSString *nameString = [NSString stringWithContentsOfFile:#"/usr/share/dict/propernames" encoding:NSUTF8StringEncoding error:NULL];
NSString *dictionary = [NSString stringWithContentsOfFile:#"/usr/share/dict/words" encoding:NSUTF8StringEncoding error:NULL];
NSArray *nameString2 = [nameString componentsSeparatedByString:#"\n"];
NSArray *dictionary2 = [dictionary componentsSeparatedByString:#"\n"];
int nsYES = 0;
int dictYES = 0;
for (NSString *n in nameString2) {
NSRange r = [n rangeOfString:name2 options:NSCaseInsensitiveSearch];
if (r.location != NSNotFound){
nsYES = 1;
}
}
for (NSString *x in dictionary2) {
NSRange l = [x rangeOfString:name2 options:NSCaseInsensitiveSearch];
if (l.location != NSNotFound){
dictYES = 1;
}
}
if (dictYES && nsYES){
NSLog(#"glen appears in both dictionaries");
}
}
}
Thanks.
Safely reading from standard input in an interactive manner in C is kind of involved. The standard functions require a fixed-size buffer, which means either some input will be too long (and corrupt your memory!) or you'll have to read in a loop. And unfortunately, Cocoa doesn't offer us a whole lot of help.
For reading standard input entirely (as in, if you're expecting an input file over standard input), there is NSFileHandle, which makes it pretty succinct. But for interactively reading and writing like you want to do here, you pretty much have to go with the linked answer for reading.
Once you have read some input into a C string, you can easily turn it into an NSString with, for example, +[NSString stringWithUTF8String:].

Trim whitespace in between characters

i just updated to ios 7 sdk, and I would like to trim/replace the whitespace between characters of a string whereby the numbers are taken out from ABAddressBook.
I have tried using the replace " " with "" code below, but this code doesnt seems to work in ios7 sdk, it works fine in ios 6 sdk by the way.
NSString *TrimmedNumberField = [self.numberField.text
stringByReplacingOccurrencesOfString:#" " withString:#""];
is there any other way I could do it in IOS 7?
EDIT:
It's a phone number type that I'm trying.
Input: "+65 12 345 6789"
The output i got from NSLog is " 12 345 6789"
I realized that when I added into NSDictionary and view it in NSLog, it appears that it contains a unix code representation of \u00a0 which is similar to the "dot in the middle" which is not equals to a fullstop.
thanks in advance.
Found the answer from here
phoneNumber = [phoneNumber stringByReplacingOccurencesOfString:#"." withString:#""];
// where #"." was created by typing Option+ Spacebar
The number is extracted from ABAddressbook.
You can loop over the string and remove whitespace as long as there is any
NSString *someString = #"A string with multiple spaces and other whitespace.";
NSMutableString *mutableCopy = [someString mutableCopy];
// get first occurance of whitespace
NSRange range = [mutableCopy rangeOfCharacterFromSet:[NSCharacterSet whitespaceCharacterSet]];
// If there is a match for the whitespace ...
while (range.location != NSNotFound) {
// ... delete it
[mutableCopy deleteCharactersInRange:range];
// and get the next whitespace
range = [mutableCopy rangeOfCharacterFromSet:[NSCharacterSet whitespaceCharacterSet]];
}
// no more whitespace. You can get back to an immutable string
someString = [mutableCopy copy];
The result with the string above is Astringwithmultiplespacesandotherwhitespace.
Try This:
NSString *str = #" untrimmed string ";
NSString *trimmed = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
Try This
[yourString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
whitespaceCharacterSet Apple Documentation for iOS says
Returns an NSData object encoding the receiver in binary format.
(NSData *)bitmapRepresentation
Return Value
An NSData object encoding the receiver in binary format.
Discussion
This format is suitable for saving to a file or otherwise transmitting or archiving.
A raw bitmap representation of a character set is a byte array of 2^16 bits (that is, 8192 bytes). The value of the bit at position n represents the presence in the character set of the character with decimal Unicode value n. To test for the presence of a character with decimal Unicode value n in a raw bitmap representation, use an expression such as the following:
So Try This
NSString *testString = #" Eek! There are leading and trailing spaces ";
NSString *trimmedString = [testString stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];

Comparing strings to keyboard input in Objective C

I'm having some trouble comparing NSStrings in Objective C. I looked at apples documentation, and it appears that there is a function that returns a boolean called isEqualToString. However, the statement never executes.
NSString* randomCombo = #"rypo";
NSFileHandle* kbd = [NSFileHandle fileHandleWithStandardInput];
NSData* inputData = [kbd availableData];
NSString* line = [[NSString alloc]initWithData : inputData encoding : NSUTF8StringEncoding];
NSLog(#"You entered: %#", line);
NSLog(#"The string to match is: %#", randomCombo);
if([line isEqualToString : randomCombo]){
NSLog(#"you win.");
}
Do I need to encode the NSString, randomCombo? Can anybody help me figure out what the problem is here?
When you use return to end your input, there's a newline character appended to the string which the other string doesn't have.
You need to either terminate input using control-D, which just closes the pipe without starting a new line, or trim the '\n' off of the string afterwards.

Creating substrings from text file

I have a text file that contains two lines of numbers, all I want to do is turn each line into a string, then add it into an array (called fields). My problem arrises when trying to find the EOF character. I can read from the file with no problem: I turn it's content into a NSString, then pass to this method.
-(void)parseString:(NSString *)inputString{
NSLog(#"[parseString] *inputString: %#", inputString);
//the end of the previous line, this is also the start of the next lien
int endOfPreviousLine = 0;
//count of how many characters we've gone through
int charCount = 0;
//while we havent gone through every character
while(charCount <= [inputString length]){
NSLog(#"[parseString] while loop count %i", charCount);
//if its an end of line character or end of file
if([inputString characterAtIndex:charCount] == '\n' || [inputString characterAtIndex:charCount] == '\0'){
//add a substring into the array
[fields addObject:[inputString substringWithRange:NSMakeRange(endOfPreviousLine, charCount)]];
NSLog(#"[parseString] string added into array: %#", [inputString substringWithRange:NSMakeRange(endOfPreviousLine, charCount)]);
//set the endOfPreviousLine to the current char count, this is where the next string will start from
endOfPreviousLine = charCount+1;
}
charCount++;
}
NSLog(#"[parseString] exited while. endOfPrevious: %i, charCount: %i", endOfPreviousLine, charCount);
}
The contents of my text file look like this:
123
456
I can get the first string (123) no problem. The call would be:
[fields addObject:[inputString substringWithRange:NSMakeRange(0, 3)]];
Next, I make the call for the second String:
[fields addObject:[inputString substringWithRange:NSMakeRange(4, 7)]];
But I get an error, and I think it is because my index is out of bounds. Since the index starts from 0, there is no index 7 (well I think its supposed to be the EOF character), and I get an error.
To sum everything up: I don't know how to deal with an index of 7 when there are only 6 characters + the EOF character.
Thanks.
You can use componentsSeparatedByCharactersInSet: to get the effect that you are looking for:
-(NSArray*)parseString:(NSString *)inputString {
return [inputString componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
}
Short answer is to use [inputString componentsSeparatedByString:#"\n"] and get the array of numbers.
Example:
Use the following code to get the lines in an array
NSString *path = [[NSBundle bundleForClass:[self class]] pathForResource:#"aaa" ofType:#"txt"];
NSString *str = [[NSString alloc] initWithContentsOfFile: path];
NSArray *lines = [str componentsSeparatedByString:#"\n"];
NSLog(#"str = %#", str);
NSLog(#"lines = %#", lines);
The above code assumes that you have a file called "aaa.txt" in your resources which is plain text file.