下划线字符串转大驼峰
时间: 2023-08-25 11:13:24 浏览: 53
要将下划线字符串转换为大驼峰形式,可以使用以下方法:
1. 将下划线字符串分割为单词列表。
2. 将每个单词的首字母转换为大写。
3. 将单词列表中的单词连接起来。
下面是一个示例代码实现:
```python
def underline_to_camel(underline_str):
words = underline_str.split('_')
camel_words = [word.capitalize() for word in words]
camel_str = ''.join(camel_words)
return camel_str
# 示例用法
underline_str = "hello_world"
camel_str = underline_to_camel(underline_str)
print(camel_str) # 输出:HelloWorld
```
在上面的示例中,`underline_to_camel` 函数将输入的下划线字符串 `"hello_world"` 转换为大驼峰形式 `"HelloWorld"` 并打印输出。你可以根据自己的需要修改输入字符串并进行测试。
相关问题
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());
}
```
字符串从驼峰式转换为下划线式
思路:
1. 遍历字符串,找到大写字母的位置;
2. 在大写字母前面插入下划线;
3. 最后将字符串转为小写。
Python 代码如下:
```python
def camel_to_underline(s):
res = ''
for i, c in enumerate(s):
if c.isupper() and i > 0:
res += '_'
res += c
return res.lower()
```
测试代码如下:
```python
s = 'camelCaseTo_under_score'
print(camel_to_underline(s)) # 输出:camel_case_to_under_score
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)