ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

如何将一个字符串中的字符提取出来(Python与C/C++)

2026/9/19 9:49:45 拓冰建站 浏览量
如何将一个字符串中的字符提取出来(Python与C/C++)

Python:

        1.使用遍历方法:

string = "Hello World"
characters = []
for char in string:characters.append(char)
print(characters)
#输出['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']

        2.使用列表推导式:

string = "Hello World"
characters = [char for char in string]
print(characters)
#输出['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']

        3.使用内置的list()函数来转换字符串为列表:

string = "Hello World"
characters = list(string)
print(characters)
#输出['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']

        4.(补充)使用split()方法将字符串拆分为字符列表:(它是将字符串以空格为分界线将其存入列表中。)

string = "Hello World !"
characters = string.split()
print(characters)
#输出['Hello', 'World', '!']

C/C++ :

        1.使用数组(char[]):

#include <iostream>
using namespace std;int main() 
{char str[20] = "Hello World"; // 定义并初始化一个字符串变量for (int i=0; str[i]; ++i) { // 通过for循环遍历每个字符cout << str[i] << endl; // 输出当前字符}printf(str)return 0;
}

        2.使用指针(char*):

#include <iostream>
using namespace std;void extractCharacters(const char *str) {while (*str != '\0') { // 判断字符串结尾标志'\0'cout << *str << endl; // 输出当前字符++str; // 移动到下一个字符位置}
}int main() {const char *str = "Hello World"; // 定义并初始化一个常量字符串指针extractCharacters(str); // 调用函数进行字符提取return 0;
}