java首尾去空格与特殊符号
时间: 2023-11-04 18:08:31 浏览: 53
Java中可以使用`trim()`方法去除字符串首尾的空格,示例如下:
```
String str = " hello world! ";
String trimmedStr = str.trim(); // 去除字符串首尾空格
System.out.println(trimmedStr); // 输出 "hello world!"
```
如果需要去除特殊符号,可以使用正则表达式替换,示例如下:
```
String str = "?!hello-world.!";
String replacedStr = str.replaceAll("[^a-zA-Z0-9\\s]", ""); // 去除非字母数字和空格的字符
System.out.println(replacedStr); // 输出 "hello world"
```
其中`[^a-zA-Z0-9\\s]`表示匹配非字母数字和空格的字符,`replaceAll()`方法可以将其替换为空字符串。
相关问题
java去除字符串首尾空格或换行符
可以使用Java中的trim()方法来去除字符串首尾的空格和换行符。例如:
```
String str = " hello world\n";
String trimmedStr = str.trim();
System.out.println(trimmedStr);
```
输出结果为:
```
hello world
```
c语言去除串首尾的空格
可以用以下代码去除C语言字符串首尾的空格:
```c
#include <stdio.h>
#include <string.h>
#include <ctype.h>
char* trim(char* str)
{
// 去除头部空格
char* ptr = str;
while (isspace(*ptr)) {
ptr++;
}
memmove(str, ptr, strlen(ptr) + 1);
// 去除尾部空格
ptr = str + strlen(str) - 1;
while (ptr >= str && isspace(*ptr)) {
ptr--;
}
*(ptr + 1) = '\0';
return str;
}
int main()
{
char str[] = " hello world ";
printf("Before trim: %s\n", str);
printf("After trim: %s\n", trim(str));
return 0;
}
```
运行结果:
```
Before trim: hello world
After trim: hello world
```