如何从字符串中获取数字字符?我不想转换</activity>
。
<uses-permission android:name="android.permission.Write_EXTERNAL_STORAGE " />
我的结果必须格式化为:
Int
答案 0 :(得分:11)
String
的unicode标量与西方阿拉伯数字您可以将unicodeScalars
的{{1}}视图与给定的String
模式进行模式匹配(例如Western Arabic numerals)。
UnicodeScalar
使用示例:
extension String {
var westernArabicNumeralsOnly: String {
let pattern = UnicodeScalar("0")..."9"
return String(unicodeScalars
.flatMap { pattern ~= $0 ? Character($0) : nil })
}
}
上面的unicode标量模式匹配方法特别有用,可以将其扩展到匹配几个给定模式中的任何一个,例如:描述Eastern Arabic numerals的不同变体的模式:
let str1 = "string_1"
let str2 = "string_20_certified"
let str3 = "a_1_b_2_3_c34"
let newStr1 = str1.westernArabicNumeralsOnly
let newStr2 = str2.westernArabicNumeralsOnly
let newStr3 = str3.westernArabicNumeralsOnly
print(newStr1) // 1
print(newStr2) // 20
print(newStr3) // 12334
这可以在实践中使用,例如如果编写一个表情符号过滤器,因为覆盖表情符号的unicode标量范围可以很容易地添加到上面东部阿拉伯语示例中的extension String {
var easternArabicNumeralsOnly: String {
let patterns = [UnicodeScalar("\u{0660}")..."\u{0669}", // Eastern Arabic
"\u{06F0}"..."\u{06F9}"] // Perso-Arabic variant
return String(unicodeScalars
.flatMap { uc in patterns.contains{ $0 ~= uc } ? Character(uc) : nil })
}
}
数组中。
patterns
模式方法而不是UnicodeScalar
方法? Swift中的Character
包含一个扩展的字形集群,它由一个或更多 Unicode标量值组成。这意味着Swift中的Character
个实例在内存中没有固定的大小,这意味着在O(1)中无法随机访问顺序(/连续)存储的字符集合中的字符,但是相反,O(n)。
Character
(CharacterView
属性)对上述方法进行基准测试与等效方法一些测试.characters
实例,很明显String
方法比UnicodeScalar
方法更快;天真测试显示执行时间差异为10-25倍,随着Character
尺寸的增长而稳步增长。
了解使用Unicode标量与Swift中的字符的限制
现在,使用String
方法存在缺点;即当处理不能由单个unicode标量表示的字符时,但是其中一个unicode标量包含在我们想要匹配的模式中。
例如,考虑一个包含四个字符的字符串 UnicodeScalar
。最后一个字符"Café"
由两个unicode标量"é"
和"e"
表示。如果我们要对"\u{301}"
实现模式匹配,则上面应用的过滤方法将允许两个unicode标量中的一个传递。
UnicodeScalar("a")...e
在本Q&amp; A中OP查询的特定用例中,上述内容不是问题,但根据用例,有时更适合使用extension String {
var onlyLowercaseLettersAthroughE: String {
let patterns = [UnicodeScalar("1")..."e"]
return String(unicodeScalars
.flatMap { uc in patterns.contains{ $0 ~= uc } ? Character(uc) : nil })
}
}
let str = "Cafe\u{301}"
print(str) // Café
print(str.onlyLowercaseLettersAthroughE) // Cae
/* possibly we'd want "Ca" or "Caé"
as result here */
模式匹配Character
。
答案 1 :(得分:4)
这是一个简单的方法,不需要 Foundation :
let newstring = String(string.characters.filter { "0"..."9" ~= $0 })
或借用@ dfri的想法使其成为String
扩展名:
extension String {
var numbers: String {
return String(characters.filter { "0"..."9" ~= $0 })
}
}
print("3 little pigs".numbers) // "3"
print("1, 2, and 3".numbers) // "123"
答案 2 :(得分:1)
这是一个Swift 2示例:
let str = "Hello 1, World 62"
let intString = str.componentsSeparatedByCharactersInSet(
NSCharacterSet
.decimalDigitCharacterSet()
.invertedSet)
.joinWithSeparator("") // Return a string with all the numbers
答案 3 :(得分:0)
例如使用正则表达式
public class DataBaseHelper extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "HOSPITALS.db";
private static final String DB_PATH_SUFFIX = "/databases/";
static Context ctx;
public DataBaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
ctx = context;
}
// Getting single contact
public Hospitals Get_ContactDetails() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM hospitalList", null);
if (cursor != null && cursor.moveToFirst()){
hosp_name.add(cursor.getString(1));
latitude.add(cursor.getDouble(6));
longitude.add(cursor.getDouble(7));
cursor.close();
db.close();
}
Hospitals cont = new Hospitals(hosp_name, latitude, longitude);
return cont;
}
public void CopyDataBaseFromAsset() throws IOException{
InputStream myInput = ctx.getAssets().open(DATABASE_NAME);
// Path to the just created empty db
String outFileName = getDatabasePath();
// if the path doesn't exist first, create it
File f = new File(ctx.getApplicationInfo().dataDir + DB_PATH_SUFFIX);
if (!f.exists())
f.mkdir();
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
private static String getDatabasePath() {
return ctx.getApplicationInfo().dataDir + DB_PATH_SUFFIX
+ DATABASE_NAME;
}
public SQLiteDatabase openDataBase() throws SQLException{
File dbFile = ctx.getDatabasePath(DATABASE_NAME);
if (!dbFile.exists()) {
try {
CopyDataBaseFromAsset();
System.out.println("Copying sucess from Assets folder");
} catch (IOException e) {
throw new RuntimeException("Error creating source database", e);
}
}
return SQLiteDatabase.openDatabase(dbFile.getPath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.CREATE_IF_NECESSARY);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
如果多次出现模式,请使用let text = "string_20_certified"
let pattern = "\\d+"
let regex = try! NSRegularExpression(pattern: pattern, options: [])
if let match = regex.firstMatch(in: text, options: [], range: NSRange(location: 0, length: text.characters.count)) {
let newString = (text as NSString).substring(with: match.range)
print(newString)
}
matches(in..
答案 4 :(得分:0)
此方法遍历字符串字符并将数字附加到新字符串:
aql> select address from company.Company where pk=2456223
[
{
"address": {
"zip": "12345",
"locality": "mytown",
"hidden": "00 01 00 00 00 FF FF FF FF 01 00 00 00 00 00 00 00 04 01 00 00 00 0E 53 79 73 74 65 6D 2E 42 6F 6F 6C 65 61 6E 01 00 00 00 07 6D 5F 76 61 6C 75 65 00 01 00 0B",
"geoID": 1234,
"streetAddress": "mystreet 4",
"region": "here",
"streetId": 5678
}
}
]
答案 5 :(得分:0)
import Foundation
let string = "a_1_b_2_3_c34"
let result = string.components(separatedBy: CharacterSet.decimalDigits.inverted).joined(separator: "")
print(result)
输出:
12334