java字符串加下划线
时间: 2024-01-15 07:11:48 浏览: 38
可以使用 String 类的 replaceAll() 方法来将字符串中的空格替换成下划线。示例如下:
```java
String str = "java string with spaces";
String newStr = str.replaceAll(" ", "_");
System.out.println(newStr); // 输出结果为:java_string_with_spaces
```
相关问题
java 字符串下划线转驼峰
以下是两种Java字符串下划线转驼峰的方法:
1.使用split()和substring()方法:
```java
public static void main(String[] args) {
String destStr = "part_vote_num";
StringBuilder sb = new StringBuilder();
String[] arr = destStr.split("_");
sb.append(arr[0]);
for (int i = 1; i < arr.length; i++) {
String temp = arr[i].substring(0, 1).toUpperCase() + arr[i].substring(1, arr[i].length());
sb.append(temp);
}
System.out.println(sb.toString());
}
```
2.使用正则表达式和Matcher类:
```java
public static void main(String[] args) {
String destStr = "part_vote_num";
Pattern p = Pattern.compile("_[a-z]");
Matcher m = p.matcher(destStr);
StringBuffer sb = new StringBuffer();
while (m.find()) {
String firstChar = m.group().substring(1, 2);
m.appendReplacement(sb, firstChar.toUpperCase());
}
m.appendTail(sb);
System.out.println(sb.toString());
}
```
java 导出字符串变成下划线
您好,如果您需要将Java中的字符串导出到文件中,并将其中的空格替换为下划线,可以使用如下代码:
```
String str = "this is an example string";
str = str.replaceAll(" ", "_");
try {
FileWriter writer = new FileWriter("output.txt");
writer.write(str);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
```
这段代码首先使用 `replaceAll()` 方法将字符串中的空格替换为下划线,然后创建一个 `FileWriter` 对象,将处理后的字符串写入到文件中。如果需要写入的是多行文本,可以使用 `BufferedWriter` 对象来实现。
希望这个答案能够帮助到您。如果您有其他问题,请随时提出。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)