How to convert string into an IP Address? - ios

I am using a function to adding . after every three characters inside the string. But how can i remove "0" in front of number.
-(NSString *)formatStringAsIpAddress:(NSString*)MacAddressWithoutColon
{
NSMutableString *macAddressWithColon = [NSMutableString new];
for (NSUInteger i = 0; i < [MacAddressWithoutColon length]; i++)
{
if (i > 0 && i % 3 == 0)
[macAddressWithColon appendString:#"."];
unichar c = [MacAddressWithoutColon characterAtIndex:i];
[macAddressWithColon appendString:[[NSString alloc] initWithCharacters:&c length:1]];
}
return macAddressWithColon;
}
If i have ip address 010.000.001.016
How can i set it up like 10.0.1.16? and if i have ip address 192.168.001.001? how to remove front 0's from IP address ?

What I would suggest:
NSString *ipAddress = #"010.000.001.016";
Split string into array of substrings:
NSArray *ipAddressComponents = [myString componentsSeparatedByString:#"."];
Run through the array with for loop and convert each to a int representation:
for(int i = 0; i < ipAddressComponents.count;i++)
{
[ipAddressComponents objectAtIndex:i] = [NSString stringWithFormat:#"%d",[[ipAddressComponents objectAtIndex:i]intValue]];
}
Join the array back into a string
NSString *newIpAddress = [ipAddressComponents componentsJoinedByString:#"."];
This should result into getting an IP address: 10.0.1.16

You can use string function and get your expected output with the help of componentsSeparatedByString and componentsJoinedByString functions.
Use below method for the same:
-(NSString*)removeZeroPrefix:(NSString*)aStrIP{
NSMutableArray *subStringArray = [[NSMutableArray alloc] init];
NSArray *arrayOfSubString = [aStrIP componentsSeparatedByString:#"."];
for (NSString *aSingleString in arrayOfSubString)
{
[subStringArray addObject:[NSNumber numberWithInteger:[aSingleString integerValue]]];
}
return [subStringArray componentsJoinedByString:#"."];
}
Usage :
[self removeZeroPrefix:#"010.000.001.016"];
[self removeZeroPrefix:#"192.168.001.001"];
Output :
Printing description of aStrIP:
10.0.1.16
Printing description of aStrIP:
192.168.1.1
hope this will helps!

In Swift
let ip = "0125.052.000.10"
let split = ip.components(separatedBy: ".")
for number in split {
if let isNumber = Int(number){
print(isNumber) // add this isNumber into array which is shows without initial zeros.
}
}
Finally join created array as String with dot Component

Related

How to convert a NSString to NSInteger with the sum of ASCII values?

In my Objective-C code I'd like to take a NSString value, iterate through the letters, sum ASCII values of the letters and return that to the user (preferably as the NSString too).
I have already written a loop, but I don't know how to get the ASCII value of an individual character. What am I missing?
- (NSString*) getAsciiSum: (NSString*) input {
NSInteger sum = 0;
for (NSInteger index=0; index<input.length; index++) {
sum = sum + (NSInteger)[input characterAtIndex:index];
}
return [NSString stringWithFormat: #"%#", sum];
}
Note: I've seen similar questions related to obtaining ASCII values, but all of them ended up displaying the value as a string. I still don't know how to get ASCII value as NSInteger.
Here is the answer:
- (NSString *) getAsciiSum: (NSString *) input
{
NSString *input = #"hi";
int sum = 0;
for (NSInteger index = 0; index < input.length; index++)
{
char c = [input characterAtIndex:index];
sum = sum + c;
}
return [NSString stringWithFormat: #"%d", sum]);
}
This is working for me.
Hope this helps!
This should work.
- (NSInteger)getAsciiSum:(NSString *)stringToSum {
int asciiSum = 0;
for (int i = 0; i < stringToSum.length; i++) {
NSString *character = [stringToSum substringWithRange:NSMakeRange(i, 1)];
int asciiValue = [character characterAtIndex:0];
asciiSum = asciiSum + asciiValue;
}
return asciiSum;
}
Thank you to How to convert a NSString to NSInteger with the sum of ASCII values? for the reference.

How to separate the sentence into words?

split the sentence into words with out using "componentsSeparatedByString:"
my word is "This is a well known simple"
I wrote like this separtedWord=[noteTextView.text componentsSeparatedByString: #" "];
but I want with out using componentsSeparatedByString.please help me
I have wrote following logic. Created two properties like this :
#property(nonatomic,strong) NSMutableArray *strings;
#property(nonatomic,strong) NSMutableString *tempString;
Wrote business logic like this :
NSString *sampleString = #"This is a well known simple";
self.tempString = [[NSMutableString alloc] init];
self.strings = [[NSMutableArray alloc] init];
for( int i = 0; i < sampleString.length; i++ )
{
unichar currentChar = [sampleString characterAtIndex:i];
NSString *character = [NSString stringWithCharacters:&currentChar length:1];
if( currentChar != ' ' )
{
[self.tempString appendString:character];
if( i == sampleString.length - 1 )
{
[self addString:self.tempString];
}
}
else
{
[self addString:self.tempString];
[self.tempString setString:#""];
}
}
NSLog(#"Array Of String = %#",self.strings);
- (void)addString:(NSString *)string
{
[self.strings addObject:[NSString stringWithString:string]];
}
2014-07-24 15:23:22.306 ViemoPlayer[1834:70b] Array Of String = (
This,
is,
a,
well,
known,
simple
)
Hope this helps.
Convert the NSString into a char array.
Loop through the array and an if statement inside, and keep appending the charecters inside the charArray into a local NSMutableString using
for(int i =0;i<[myCharArray count];i++){
NSMutableString *teststring;
[teststring appendString:[myCharArray objectAtIndex : i]];
if([myCharArray objectAtIndex] == " "){
NSLog(teststring);
teststring = #""; //emptying the testString when we get a space
}
}
That should do it

Create string based on characters expected

I would like to create a string based on the number of characters passed in. Each character passed in will be a "X". So for example, if the length passed in is 5, then the string created should be
NSString *testString=#"XXXXX";
if it is 2 then it would be
NSString *testString=#"XX";
Can anyone tell me what the most efficient way to do this would be?
Thank you!
If you know the maximum length is some reasonable number then you could do something simple like this:
- (NSString *)xString:(NSUInteger)length {
static NSString *xs = #"XXXXXXXXXXXXXXXXXXXXXXXXXXX";
return [xs substringToIndex:length];
}
NSString *str = [self xString:5]; // str will be #"XXXXX";
If you pass in too large of a length, the app will crash - add more Xs to xs.
This approach is more efficient than building up an NSMutableString but it does make an assumption about the maximum length you might need.
- (NSString *)stringOf:(NSString *)str times:(NSInteger)count
{
NSMutableString *targ = [[NSMutableString alloc] initWithCapacity:count];
for (int i=0; i < count; i++)
{
[targ appendString:str];
}
return targ;
}
and
[self stringOf:#"X" times:4];
note that initWithCapacity: (in performance manner) better than init. But I guess that's all for efficiency.
The way I would do it is
NSMutableString *xString = [[NSMutableString alloc] init];
while ( int i = 0; i < testString.length; i++ ) {
[xString appendString:#"X"];
i++;
}
NSUInteger aLength. // assume this is the argument
NSMutableString *xStr = [NSMutableString stringWithCapacity: aLength];
for ( NSUInteger i = 0; i < aLength; i++ ) {
[xStr appendFormat:#"X"];
}
The following will do what you ask in one call:
NSString *result = [#"" stringByPaddingToLength:numberOfCharsWanted
withString:characterToRepeat
startingAtIndex:0];
where numberOfCharsWanted is an NSUInteger and characterToRepeat is an NSString containing the character.

Issue with UITextfield into a NSMutableArray

I had this working using NSArray until I realize I need to insert a string into array. Now I'm changing this to a NSMutableArray, but having issues with my syntax. Am I allowed to use componentsJoinedByString in NSMutable arrays?
NSString *item;
int numofSeg;
int needSeg;
if (textfield.text == #"::") {
numofSeg = 0;
}
NSMutableArray *dlist = [[NSMutableArray alloc]init];
//take string from textfield and split it into a list on colons.
dlist = [textfield.text componentsSeparatedByString:#":"];
//run through list to count how many segments. Non blank ones.
for (item in dlist) {
if (item != #""){
numofSeg = numofSeg + 1;
NSLog(#"%#",numofSeg);
}
}
//determine number of segments
needSeg = 8 - numofSeg;
while (needSeg > 0) {
//insert 0000 at blank spot
[dlist insertString:#"0000" atIndex:#""];
needSeg = needSeg - 1;
}
for (item in dlist) {
if (item == #"") {
//remove blank spaces from list
[dlist removeAllObjects:item];
}
}
//join the list of times into a string with colon
NSString *joinstring = [dlist componentsJoinedByString:#":"];
NSLog(#"%#",joinstring);
I don't think NSMutableArray has a method called insertString:atIndex:. You should probably use insertObject:atIndex: instead.
What error do you get exactly?
Edit:
If you only use the NSMutableArray to insert #"0000" before #" ", then you can simply do:
string = [string stringByReplacingOccurrencesOfString:#" " withString:#" 0000"];
or something like that. No need to use NSMutableArray.
I finally figured it out. This is what I ended up using to fix this:
NSString *z = #"0000";
z = [z stringByAppendingString:#""];

How to split string into substrings on iOS?

I received an NSString from the server. Now I want to split it into the substring which I need.
How to split the string?
For example:
substring1:read from the second character to 5th character
substring2:read 10 characters from the 6th character.
You can also split a string by a substring, using NString's componentsSeparatedByString method.
Example from documentation:
NSString *list = #"Norman, Stanley, Fletcher";
NSArray *listItems = [list componentsSeparatedByString:#", "];
NSString has a few methods for this:
[myString substringToIndex:index];
[myString substringFromIndex:index];
[myString substringWithRange:range];
Check the documentation for NSString for more information.
I wrote a little method to split strings in a specified amount of parts.
Note that it only supports single separator characters. But I think it is an efficient way to split a NSString.
//split string into given number of parts
-(NSArray*)splitString:(NSString*)string withDelimiter:(NSString*)delimiter inParts:(int)parts{
NSMutableArray* array = [NSMutableArray array];
NSUInteger len = [string length];
unichar buffer[len+1];
//put separator in buffer
unichar separator[1];
[delimiter getCharacters:separator range:NSMakeRange(0, 1)];
[string getCharacters:buffer range:NSMakeRange(0, len)];
int startPosition = 0;
int length = 0;
for(int i = 0; i < len; i++) {
//if array is parts-1 and the character was found add it to array
if (buffer[i]==separator[0] && array.count < parts-1) {
if (length>0) {
[array addObject:[string substringWithRange:NSMakeRange(startPosition, length)]];
}
startPosition += length+1;
length = 0;
if (array.count >= parts-1) {
break;
}
}else{
length++;
}
}
//add the last part of the string to the array
[array addObject:[string substringFromIndex:startPosition]];
return array;
}

Resources