字符串查找子串

一、字符串查找子串函數

在編寫字符串處理程序時,字符串查找子串函數是非常實用的。在C++中,常用的字符串查找子串函數為std::string::find()。這個函數可以用來查找字符串中的子串。例如:

std::string str = "hello world";
int index = str.find("world");

這個例子中,我們定義了一個字符串str,並使用std::string::find()函數查找其中的子串”world”,得到了這個子串在字符串中的位置。

在Python中,可以使用字符串自帶的方法find()來查找子串,例如:

str = "hello world"
index = str.find("world")

二、字符串查找子串的個數

有時候我們需要統計字符串中子串出現的次數,C++和Python都提供了方法用來實現這個功能。

在C++中,我們可以使用std::string::find()函數和循環來查找字符串中子串出現的次數。例如:

std::string str = "hello world";
std::string substr = "l";
int count = 0;
size_t pos = 0;
while ((pos = str.find(substr, pos)) != std::string::npos) {
    ++count;
    pos += substr.length();
}

這個代碼段中,我們定義了一個變量count來保存查找到的子串的個數,然後使用循環和std::string::find()函數來查找每個子串出現的位置,並將count加一。

在Python中,可以使用字符串自帶的方法count()來查找子串的個數。例如:

str = "hello world"
substr = "l"
count = str.count(substr)

三、字符串查找子串可以使用index

在Python中,字符串自帶的方法index()也可以用來查找子串。與find()函數不同的是,當子串不存在時,index()函數會拋出一個異常,而find()函數會返回std::string::npos。例如:

str = "hello world"
index = str.index("world")

四、字符串查找子串出現次數

除了統計子串出現的次數外,有時候我們還需要知道每個子串出現的位置。在C++中,可以使用std::string::find()函數和std::vector來實現這個功能。例如:

std::string str = "hello world";
std::string substr = "l";
size_t pos = 0;
std::vector indices;
while ((pos = str.find(substr, pos)) != std::string::npos) {
    indices.push_back(pos);
    pos += substr.length();
}

這個代碼段中,我們定義了一個std::vector來保存查找到的子串的位置,然後使用循環和std::string::find()函數來查找每個子串出現的位置,並將位置保存到vector中。

在Python中,可以使用字符串自帶的方法finditer()來查找子串出現的位置。這個方法返回一個生成器,可以使用for循環來遍歷每個子串的位置。例如:

str = "hello world"
substr = "l"
indices = [m.start() for m in re.finditer(substr, str)]

五、字符串查找子串最快算法

在C++中,可以使用KMP算法來實現字符串查找子串功能。KMP算法是一種線性時間複雜度的算法,比std::string::find()函數更快,特別是對於長字符串和重複出現的子串。KMP算法的基本思想是在匹配的過程中,當發現不匹配時,不需要回溯,而是通過已經匹配的信息,直接跳過一部分文本。

以下是KMP算法的實現代碼:

void computeLPSArray(std::string substr, int* lps) {
    int len = 0;
    lps[0] = 0;
    int i = 1;
    while (i < substr.length()) {
        if (substr[i] == substr[len]) {
            ++len;
            lps[i] = len;
            ++i;
        } else {
            if (len != 0) {
                len = lps[len-1];
            } else {
                lps[i] = 0;
                ++i;
            }
        }
    }
}
int KMP(std::string str, std::string substr) {
    int n = str.length();
    int m = substr.length();
    int lps[m];
    computeLPSArray(substr, lps);
    int i = 0;
    int j = 0;
    while (i < n) {
        if (substr[j] == str[i]) {
            ++i;
            ++j;
        }
        if (j == m) {
            return i-j;
        } else if (i < n && substr[j] != str[i]) {
            if (j != 0) {
                j = lps[j-1];
            } else {
                ++i;
            }
        }
    }
   return -1;
}

在Python中,也可以使用KMP算法來實現字符串查找子串功能。例如:

def computeLPSArray(substr):
    len = 0
    lps = [0] * len(substr)
    i = 1
    while i < len(substr):
        if substr[i] == substr[len]:
            len += 1
            lps[i] = len
            i += 1
        else:
            if len != 0:
                len = lps[len-1]
            else:
                lps[i] = 0
                i += 1
    return lps
def KMP(str, substr):
    n = len(str)
    m = len(substr)
    lps = computeLPSArray(substr)
    i = 0
    j = 0
    while i < n:
        if substr[j] == str[i]:
            i += 1
            j += 1
        if j == m:
            return i-j
        elif i < n and substr[j] != str[i]:
            if j != 0:
                j = lps[j-1]
            else:
                i += 1
    return -1

六、字符串查找子串算法

除了KMP算法,還有其他算法可以用來實現字符串查找子串功能。例如,Brute-Force算法就是一種樸素的算法,在每個位置都嘗試查找子串,並比較字母。這種算法的時間複雜度為O(mn),其中m是子串長度,n是字符串長度,效率較低。

以下是Brute-Force算法的實現代碼:

int BruteForce(std::string str, std::string substr) {
    int n = str.length();
    int m = substr.length();
    for (int i=0; i<=n-m; ++i) {
        int j;
        for (j=0; j<m; ++j) {
            if (str[i+j] != substr[j]) {
                break;
            }
        }
        if (j == m) {
            return i;
        }
    }
    return -1;
}

七、字符串查找子串C代碼

以下是使用std::string::find()函數實現字符串查找子串的C代碼:

#include <stdio.h>
#include <string.h>

int main() {
    char str[20] = "hello world";
    char substr[10] = "world";
    char* p = strstr(str, substr);
    if (p) {
        printf("%s found at position %d.\n", substr, p-str);
    } else {
        printf("%s not found.\n", substr);
    }
    return 0;
}

八、字符串查找子串Python

以下是使用字符串自帶方法find()實現字符串查找子串的Python代碼:

str = "hello world"
substr = "world"
index = str.find(substr)
if index != -1:
    print(substr, "found at position", index)
else:
    print(substr, "not found.")

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/257788.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-12-15 12:46
下一篇 2024-12-15 12:46

相關推薦

  • Python字符串寬度不限制怎麼打代碼

    本文將為大家詳細介紹Python字符串寬度不限制時如何打代碼的幾個方面。 一、保持代碼風格的統一 在Python字符串寬度不限制的情況下,我們可以寫出很長很長的一行代碼。但是,為了…

    編程 2025-04-29
  • Python中將字符串轉化為浮點數

    本文將介紹在Python中將字符串轉化為浮點數的常用方法。在介紹方法之前,我們先來思考一下這個問題應該如何解決。 一、eval函數 在Python中,最簡單、最常用的將字符串轉化為…

    編程 2025-04-29
  • Java判斷字符串是否存在多個

    本文將從以下幾個方面詳細闡述如何使用Java判斷一個字符串中是否存在多個指定字符: 一、字符串遍歷 字符串是Java編程中非常重要的一種數據類型。要判斷字符串中是否存在多個指定字符…

    編程 2025-04-29
  • Python學習筆記:去除字符串最後一個字符的方法

    本文將從多個方面詳細闡述如何通過Python去除字符串最後一個字符,包括使用切片、pop()、刪除、替換等方法來實現。 一、字符串切片 在Python中,可以通過字符串切片的方式來…

    編程 2025-04-29
  • Python如何將字符串1234變成數字1234

    Python作為一種廣泛使用的編程語言,對於數字和字符串的處理提供了很多便捷的方式。如何將字符串「1234」轉化成數字「1234」呢?下面將從多個方面詳細闡述Python如何將字符…

    編程 2025-04-29
  • Python int轉二進制字符串

    本文將從以下幾個方面對Python中將int類型轉換為二進制字符串進行詳細闡述: 一、int類型和二進制字符串的定義 在Python中,int類型表示整數,二進制字符串則是由0和1…

    編程 2025-04-29
  • 用title和capitalize美觀處理Python字符串

    在Python中,字符串是最常用的數據類型之一。對字符串的美觀處理是我們在實際開發中經常需要的任務之一。Python內置了一些方法,如title和capitalize,可以幫助我們…

    編程 2025-04-28
  • Python 提取字符串中的電話號碼

    Python 是一種高級的、面向對象的編程語言,它具有簡單易學、開發迅速、代碼簡潔等特點,廣泛應用於 Web 開發、數據科學、人工智能等領域。在 Python 中,提取字符串中的電…

    編程 2025-04-28
  • Python如何打印帶雙引號的字符串

    Python作為一種廣泛使用的編程語言,在日常開發中經常需要打印帶雙引號的字符串。那麼,如何打印帶雙引號的字符串呢? 一、使用轉義字符 在Python中,我們可以通過使用轉義字符\…

    編程 2025-04-28
  • Python字符串反轉函數用法介紹

    本文將從多個方面詳細講解Python字符串反轉函數,幫助開發者更好的理解和運用。 一、簡介 在Python中,字符串是最基本的數據類型之一。反轉字符串,在開發中也是常見的操作之一。…

    編程 2025-04-28

發表回復

登錄後才能評論