objective 字符串与c语言的串转化
来源:互联网 发布:广州城建职业学院网络 编辑:程序博客网 时间:2024/05/17 23:36
1.地址:
https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Strings/Articles/CreatingStrings.html
2.使用sudzc连接webService时出现了中文乱码问题,使用NSUTF8encoding 依然是乱码。
使用上面的EncodeUTF8Str方法转码,比如:苹果,转码后是 %E8%8B%B9%E6%9E%9C,这样服务器端解码就可以了。
#pragma mark -
#pragma mark Encode Chinese to ISO8859-1 in URL
-(NSString *)EncodeUTF8Str:(NSString *)encodeStr{
CFStringRef nonAlphaNumValidChars = CFSTR("![ DISCUZ_CODE_1 ]’()*+,-./:;=?@_~");
NSString *preprocessedString = (NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault, (CFStringRef)encodeStr, CFSTR(""), kCFStringEncodingUTF8);
NSString *newStr = [(NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)preprocessedString,NULL,nonAlphaNumValidChars,kCFStringEncodingUTF8) autorelease];
[preprocessedString release];
return newStr;
}
#pragma mark -
#pragma mark Encode Chinese to GB2312 in URL
-(NSString *)EncodeGB2312Str:(NSString *)encodeStr{
CFStringRef nonAlphaNumValidChars = CFSTR("![ DISCUZ_CODE_1 ]’()*+,-./:;=?@_~");
NSString *preprocessedString = (NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault, (CFStringRef)encodeStr, CFSTR(""), kCFStringEncodingGB_18030_2000);
NSString *newStr = [(NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)preprocessedString,NULL,nonAlphaNumValidChars,kCFStringEncodingGB_18030_2000) autorelease];
[preprocessedString release];
return newStr;
}
3. 普通char* 与 Objective c 转化
Creating and Converting String Objects
NSString
and its subclassNSMutableString
provide several ways to create string objects, most based around the various character encodings it supports. Although string objects always present their own contents as Unicode characters, they can convert their contents to and from many other encodings, such as 7-bit ASCII, ISO Latin 1, EUC, and Shift-JIS. TheavailableStringEncodings
class method returns the encodings supported. You can specify an encoding explicitly when converting a C string to or from a string object, or use the default C string encoding, which varies from platform to platform and is returned by thedefaultCStringEncoding
class method.
Creating Strings
The simplest way to create a string object in source code is to use the Objective-C @"..."
construct:
NSString *temp = @"Contrafibularity";
Note that, when creating a string constant in this fashion, you should use UTF-8 characters. Such an object is created at compile time and exists throughout your program’s execution. The compiler makes such object constants unique on a per-module basis, and they’re never deallocated. You can also send messages directly to a string constant as you do any other string:
BOOL same = [@"comparison" isEqualToString:myString];
NSString from C Strings and Data
To create anNSString
object from a C string, you use methods such as initWithCString:encoding:
. You must correctly specify the character encoding of the C string. Similar methods allow you to create string objects from characters in a variety of encodings. The methodinitWithData:encoding:
allows you to convert string data stored in anNSData
object into an NSString
object.
char *utf8String = /* Assume this exists. */ ;
NSString *stringFromUTFString = [[NSString alloc] initWithUTF8String:utf8String];
char *macOSRomanEncodedString = /* assume this exists */ ;
NSString *stringFromMORString =
[[NSString alloc] initWithCString:macOSRomanEncodedString
encoding:NSMacOSRomanStringEncoding];
NSData *shiftJISData = /* assume this exists */ ;
NSString *stringFromShiftJISData =
[[NSString alloc] initWithData:shiftJISData
encoding:NSShiftJISStringEncoding];
The following example converts an NSString
object containing a UTF-8 character to ASCII data then back to anNSString
object.
unichar ellipsis = 0x2026;
NSString *theString = [NSString stringWithFormat:@"To be continued%C", ellipsis];
NSData *asciiData = [theString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *asciiString = [[NSString alloc] initWithData:asciiData encoding:NSASCIIStringEncoding];
NSLog(@"Original: %@ (length %d)", theString, [theString length]);
NSLog(@"Converted: %@ (length %d)", asciiString, [asciiString length]);
// output:
// Original: To be continued… (length 16)
// Converted: To be continued... (length 18)
Note: NSString
is not intended as a data storage container for arbitrary sequences of bytes. For this type of functionality, refer toNSData
.
Variable Strings
To create a variable string, you typically use stringWithFormat:
: or initWithFormat:
(or for localized strings, localizedStringWithFormat:
). These methods and their siblings use a format string as a template into which the values you provide (string and other objects, numerics values, and so on) are inserted. They and the supported format specifiers are described in“Formatting String Objects.”
You can build a string from existing string objects using the methods stringByAppendingString:
and stringByAppendingFormat:
to create a new string by adding one string after another, in the second case using a format string.
NSString *hString = @"Hello";
NSString *hwString = [hString stringByAppendingString:@", world!"];
Strings to Present to the User
When creating strings to present to the user, you should consider the importance oflocalizing your application. In general, you should avoid creating user-visible strings directly in code. Instead you should use strings in your code as a key to a localization dictionary that will supply the user-visible string in the user's preferred language. Typically this involves usingNSLocalizedString
and similar macros, as illustrated in the following example.
NSString *greeting = NSLocalizedStringFromTable
(@"Hello", @"greeting to present in first launch panel", @"greetings");
For more about internationalizing your application, see Internationalization Programming Topics. “Localizing String Resources” describes how to work with and reorder variable arguments in localized strings.
Combining and Extracting Strings
You can combine and extract strings in various ways. The simplest way to combine two strings is to append one to the other. ThestringByAppendingString:
method returns a string object formed from the receiver and the given argument.
NSString *beginning = @"beginning";
NSString *alphaAndOmega = [beginning stringByAppendingString:@" and end"];
// alphaAndOmega is @"beginning and end"
You can also combine several strings according to a template with the initWithFormat:
,stringWithFormat:
, and stringByAppendingFormat:
methods; these are described in more detail in “Formatting String Objects.”
You can extract substrings from the beginning or end of a string to a particular index, or from a specific range, with thesubstringToIndex:
,substringFromIndex:
, and substringWithRange:
methods. You can also split a string into substrings (based on a separator string) with thecomponentsSeparatedByString:
method. These methods are illustrated in the following examples—notice that the index of the index-based methods starts at0
:
NSString *source = @"0123456789";
NSString *firstFour = [source substringToIndex:4];
// firstFour is @"0123"
NSString *allButFirstThree = [source substringFromIndex:3];
// allButFirstThree is @"3456789"
NSRange twoToSixRange = NSMakeRange(2, 4);
NSString *twoToSix = [source substringWithRange:twoToSixRange];
// twoToSix is @"2345"
NSArray *split = [source componentsSeparatedByString:@"45"];
// split contains { @"0123", @"6789" }
If you need to extract strings using pattern-matching rather than an index, you should use a scanner—see“Scanners.”
Getting C Strings
To get a C string from a string object, you are recommended to useUTF8String
. This returns aconst char *
using UTF8 string encoding.
const char *cString = [@"Hello, world" UTF8String];
The C string you receive is owned by a temporary object, and will become invalid when automatic deallocation takes place. If you want to get a permanent C string, you must create a buffer and copy the contents of theconst char *
returned by the method.
Similar methods allow you to create string objects from characters in the Unicode encoding or an arbitrary encoding, and to extract data in these encodings.initWithData:encoding:
anddataUsingEncoding:
perform these conversions from and toNSData
objects.
Conversion Summary
This table summarizes the most common means of creating and converting string objects:
Source
Creation method
Extraction method
In code
@"..."
compiler construct
N/A
UTF8 encoding
stringWithUTF8String:
UTF8String
Unicode encoding
stringWithCharacters:length:
getCharacters:
getCharacters:range:
Arbitrary encoding
initWithData:encoding:
dataUsingEncoding:
Existing strings
stringByAppendingString:
stringByAppendingFormat:
N/A
Format string
localizedStringWithFormat:
initWithFormat:locale:
Use NSScanner
Localized strings
NSLocalizedString
and similar
N/A
- objective 字符串与c语言的串转化
- Objective-c 字符串与整型相互转化
- 关于字符串与数字的转化(C语言)
- c的数字与字符串的转化
- objective c 整型和字符串相互转化
- C C++ 数字与字符串的转化
- C语言字符串与数字转化(T函数系列)
- C语言实现atoi和itoa(字符串与数字之间的转化)
- 【C语言】数字的字符串转化为 数字
- (c语言)字符串的大小写字母转化函数
- C语言中数组转化为字符串的方法
- 字符串如何转化为对应的枚举值 C语言
- C语言中将字符串转化为数字的函数总结
- c语言中怎么实现字符串转化数字的功能
- C语言 字符串和C++ string对象的相互转化
- C语言的字符串转化为整型:atoi
- Objective-c语言_对字符串操作的常用方法
- Objective-C语言_对字符串操作的常用方法
- [chromium][browser][idea][closed]把Android Browser导入Eclipse中运行调试
- C语言中动态的申请二(三)及多维数组的使用方法及释放方法
- 多终端WEB页面字体处理方法总结
- 庄表伟:谈谈大家是怎么玩Github的
- Insert Interval
- objective 字符串与c语言的串转化
- 电子邮件解惑之邮件传输协议(smtp)
- android开发 软键盘出现后 防止EditText控件遮挡 整体平移UI
- 【Leetcode】Letter Combinations of a Phone Number
- [C++]MySQL数据库操作实例
- IOS开发中UITableView和UITableViewCell的几种样式
- 请问21世纪最嗨的东西是什么?
- 双系统下重装Windows后,如何恢复Ubuntu
- mysql 管理工具