删除字符串
时间: 2023-08-21 22:07:44 浏览: 35
要删除字符串,可以使用编程语言中的字符串处理函数或方法。以下是几个示例:
在 Python 中,可以使用 `replace()` 方法来删除字符串中的子字符串:
```
string = "hello world"
new_string = string.replace("world", "")
print(new_string) # 输出:hello
```
在 Java 中,可以使用 `replaceAll()` 方法来删除字符串中的子字符串:
```
String str = "hello world";
String newStr = str.replaceAll("world", "");
System.out.println(newStr); // 输出:hello
```
在 C++ 中,可以使用 `erase()` 方法来删除字符串中的字符:
```
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "hello world";
str.erase(5, 6);
cout << str << endl; // 输出:hello
return 0;
}
```
这些只是示例,具体实现方式可能因编程语言而异。
相关问题
python 删掉字符串空格
在 Python 中,可以使用 `strip()` 方法来删除字符串两侧的空格,使用 `lstrip()` 方法来删除字符串左侧的空格,使用 `rstrip()` 方法来删除字符串右侧的空格。
示例代码如下:
```python
str1 = " hello world "
print(str1.strip()) # 输出 "hello world"
print(str1.lstrip()) # 输出 "hello world "
print(str1.rstrip()) # 输出 " hello world"
```
如果要删除字符串中间的空格,可以使用 `replace()` 方法来替换空格为空字符串,示例代码如下:
```python
str1 = "hello world"
str2 = str1.replace(" ", "")
print(str2) # 输出 "helloworld"
```
c语言字符串删除字符串
以下是两种C语言删除字符串的方法:
方法一:函数方法
```c
void delchar(char *str, char c) {
int i, j;
for (i = j = 0; str[i] != '\0'; i++) {
if (str[i] != c) {
str[j++] = str[i];
}
}
str[j] = '\0';
}
```
该方法只需要进行一次对目标字符串的遍历即可完成删除目标字符的功能。
方法二:利用字符数组
```c
#include <stdio.h>
#include <string.h>
int main() {
char a[100], b[100];
int pos, i, len;
printf("请输入一个字符串:");
gets(a);
len = strlen(a);
printf("请输入要删除的字符:");
scanf("%c", &b[0]);
for (i = 0; i < len; i++) {
if (a[i] == b[0]) {
pos = i;
break;
}
}
for (i = 0; i < len; i++) {
if (i == pos) {
continue;
}
printf("%c", a[i]);
}
return 0;
}
```
该方法需要定义两个字符数组a和b,以及标志删除位置的int型pos。首先用gets函数输入数组a的值,并利用for循环回将数组a copy到数组b。然后利用for循环,令pos位的数组b元素赋值到a。