如何在Swift中将字符串“Hello”转换为数组[“H”,“e”,“l”,“l”,“o”]?
在Objective-C中我使用过:
NSMutableArray *characters = [[NSMutableArray alloc] initWithCapacity:[myString length]];
for (int i=0; i < [myString length]; i++) {
NSString *ichar = [NSString stringWithFormat:@"%c", [myString characterAtIndex:i]];
[characters addObject:ichar];
}
答案 0 :(得分:278)
在Swift中更容易:
let string : String = "Hello "
let characters = Array(string)
println(characters)
// [H, e, l, l, o, , , , , ]
这使用了
的事实Array
和SequenceType
String
符合SequenceType
协议及其序列生成器
枚举字符。由于Swift字符串完全支持Unicode,因此即使使用字符也是如此 在“基本多语言平面”之外(例如)和扩展的字形 集群(例如,实际上由两个 Unicode标量组成)。
更新:自Swift 2起, String
不再符合
SequenceType
,但characters
属性提供了序列
Unicode字符:
let string = "Hello "
let characters = Array(string.characters)
print(characters)
这也适用于 Swift 3 。
更新:自Swift 4起, String
(再次)是其收藏品
Character
S:
let string = "Hello "
let characters = Array(string)
print(characters)
// ["H", "e", "l", "l", "o", " ", "", "", " ", ""]
答案 1 :(得分:83)
在Swift 4中,您不必使用characters
来使用map()
。只需对String进行map()
。
let letters = "ABC".map { String($0) }
print(letters) // ["A", "B", "C"]
print(type(of: letters)) // Array<String>
或者如果你更喜欢更短:"ABC".map(String.init)
(2字节)
在Swift 2和Swift 3中,您可以将map()
函数用于characters
属性。
let letters = "ABC".characters.map { String($0) }
print(letters) // ["A", "B", "C"]
接受的答案似乎不是最好的,因为序列转换的String
不是String
序列,而是Character
:
$ swift
Welcome to Swift! Type :help for assistance.
1> Array("ABC")
$R0: [Character] = 3 values {
[0] = "A"
[1] = "B"
[2] = "C"
}
以下内容对我有用:
let str = "ABC"
let arr = map(str) { s -> String in String(s) }
全局函数map()
的参考位于:http://swifter.natecook.com/func/map/
答案 2 :(得分:10)
String上还有这个有用的功能:组件(separatedBy:String)
let string = "1;2;3"
let array = string.components(separatedBy: ";")
print(array) // returns ["1", "2", "3"]
很好地处理由&#34;;&#34;等字符分隔的字符串。甚至&#34; \ n&#34;
答案 3 :(得分:5)
更新了Swift 4
以下是3种方法。
//array of Characters
let charArr1 = [Character](myString)
//array of String.element
let charArr2 = Array(myString)
for char in myString {
//char is of type Character
}
在某些情况下,人们真正想要的是一种将字符串转换为每个字符长度为1的字符串数组的方法。这是一种超级有效的方法:
//array of String
var strArr = myString.map { String($0)}
Swift 3
以下是3种方法。
let charArr1 = [Character](myString.characters)
let charArr2 = Array(myString.characters)
for char in myString.characters {
//char is of type Character
}
在某些情况下,人们真正想要的是一种将字符串转换为每个字符长度为1的字符串数组的方法。这是一种超级有效的方法:
var strArr = myString.characters.map { String($0)}
或者您可以为String添加扩展名。
extension String {
func letterize() -> [Character] {
return Array(self.characters)
}
}
然后你可以这样称呼它:
let charArr = "Cat".letterize()
答案 4 :(得分:5)
一种简单的方法是map
变量并将每个Character
作为String
返回:
let someText = "hello"
let array = someText.map({ String($0) }) // [String]
输出应为["h", "e", "l", "l", "o"]
。
答案 5 :(得分:4)
let string = "hell0"
let ar = Array(string.characters)
print(ar)
答案 6 :(得分:2)
Martin R回答是最好的方法,正如他所说,因为String符合SquenceType协议,你也可以枚举一个字符串,在每次迭代时获取每个字符。
let characters = "Hello"
var charactersArray: [Character] = []
for (index, character) in enumerate(characters) {
//do something with the character at index
charactersArray.append(character)
}
println(charactersArray)
答案 7 :(得分:2)
在Swift 4中,由于String
是Character
的集合,您需要使用map
let array1 = Array("hello") // Array<Character>
let array2 = Array("hello").map({ "\($0)" }) // Array<String>
let array3 = "hello".map(String.init) // Array<String>
答案 8 :(得分:1)
您还可以创建扩展程序:
var strArray = "Hello, playground".Letterize()
extension String {
func Letterize() -> [String] {
return map(self) { String($0) }
}
}
答案 9 :(得分:1)
func letterize() -> [Character] {
return Array(self.characters)
}
答案 10 :(得分:0)
针对String:components(separatedBy:String)上的函数
在Swift 5.1中
已更改为:
string.split(separator: "/")
答案 11 :(得分:0)
假设您有四个文本字段“ otpOneTxt”,“ otpTwoTxt”,“ otpThreeTxt”,“ otpFourTxt”和字符串“ getOtp”
include <iostream>
#include <vector>
using namespace std;
class IMovable
{
public:
virtual bool canFly ()
{
return false;
}
virtual bool canSwim ()
{
return false;
}
virtual bool canCrawl ()
{
return false;
}
};
class IFlying: virtual public IMovable
{
public:
virtual void fly () = 0;
};
class IAquatic: virtual public IMovable
{
public:
virtual void swim () = 0;
};
class ITerrestrial: virtual public IMovable
{
public:
virtual void crawl () = 0;
};
class Animal
{
public:
void eat ()
{
cout << "Yummy";
}
};
class Bird:public Animal, public IFlying
{
public:
void fly () override
{
cout << "Fly like a bird";
}
bool canFly () override
{
return true;
}
};
class Frog:public Animal, public IAquatic, public ITerrestrial
{
public:
void swim () override
{
cout << "Swimming frog";
}
void crawl () override
{
cout << "Ribbit";
}
bool canSwim () override
{
return true;
}
bool canCrawl () override
{
return true;
}
};
main ()
{
std::vector < IMovable * >animals;
Frog f;
Bird b;
animals.push_back (&f);
animals.push_back (&b);
for (auto animal:animals)
{
if (animal->canCrawl ())
{
static_cast < ITerrestrial * >(animal)->crawl ();
}
if (animal->canSwim ())
{
static_cast < IAquatic * >(animal)->swim ();
}
if (animal->canFly ())
{
static_cast < IFlying * >(animal)->fly ();
}
return 0;
}
}
答案 12 :(得分:-1)
let str = "cdcd"
let characterArr = str.reduce(into: [Character]()) { result, letter in
result.append(letter)
}
print(characterArr)
//["c", "d", "c", "d"]