通过删除“ \”将字符串转换为URL

时间:2019-01-30 05:32:50

标签: ios swift url

我想从特定字符串的开头和结尾删除\",以获得实际的URL

代码: let = subString = originalString.replacingOccurrences(of: "\", with: "")

  

“ \” https://api.example.com/deep-link?url=some_url_encoded_string \“”

我想要的是:

  

https://api.example.com/deep-link?url=some_url_encoded_string

5 个答案:

答案 0 :(得分:2)

您可以修剪字符串以删除所有前导和尾随引号:

let url = "\"https://some-server/some/path\""
let processedString = str.trimmingCharacters(in: .init(charactersIn: "\""))
print(processedString) // https://some-server/some/path

请注意,\"不是由两个字符组成的字符串,而是引号的转义序列。

答案 1 :(得分:0)

如果要删除字符串中出现的\",请使用以下命令:

let subString = originalString.replacingOccurrences(of: "\"", with: "")

如果要仅在字符串的开头和结尾将其删除,则将进行检查:

if originalString.first == "\"" {
    _ = originalString.removeFirst()
}
if originalString.last == "\"" {
    _ = originalString.popLast() 
}

答案 2 :(得分:0)

您必须删除字符“。

那样。

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="90dp"
    android:layout_height="90dp"
    xmlns:app="http://schemas.android.com/apk/res-auto">

   <!-- Please note on the tag "touchable" which we must pass as param in constructor to let our listener know which part of the item will be listening to touch event -->
    <View
        android:tag="touchable"
        android:id="@+id/v_background"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="@drawable/bkg_corner_gray"
        app:layout_constraintWidth_percent="0.78846153846"
        app:layout_constraintDimensionRatio="1"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"/>

    <TextView
        android:id="@+id/tv_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ellipsize="end"
        android:maxLines="1"
        android:textSize="35sp"
        android:textColor="@color/black"
        app:layout_constraintStart_toStartOf="@id/v_background"
        app:layout_constraintEnd_toEndOf="@id/v_background"
        app:layout_constraintTop_toTopOf="@id/v_background"
        app:layout_constraintBottom_toBottomOf="@id/v_background"/>

</android.support.constraint.ConstraintLayout>

答案 3 :(得分:0)

这里的反斜杠只是因为您需要在字符串中使用双引号,否则在Swift 4.2或更早版本的一行中声明的字符串中将不可能使用双引号。


在Swift 5中,您可以使用原始字符串文字

let originalString = #""https...""#

因此,您实际上只需要删除实际上在字符串中且为双引号的字符(简化后的字符:\" = ")。

为此,您必须在双引号"\"-> "\""

前再次使用反斜杠
let subString = originalString.replacingOccurrences(of: "\"", with: "")

答案 4 :(得分:0)

  

检查以下代码

let originalString = "\"https://api.example.com/deep-link?url=some_url_encoded_string\""

var temp = "\("\"")" as? String

if originalString.hasPrefix(temp!){
    originalString.replacingOccurrences(of: "\"", with: "")
}