字符串从驼峰式转换为下划线式
时间: 2023-12-23 07:02:37 浏览: 27
思路:
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
```
相关问题
ts 字符串从驼峰式转换为下划线式
思路:
1. 遍历字符串中的每个字符,判断如果是大写字母,则在前面加上下划线,并将该字母转为小写字母。
2. 否则直接将该字符加入新字符串中。
示例代码:
```python
def camel_to_snake(s):
res = ""
for i, c in enumerate(s):
if c.isupper():
if i != 0:
res += "_"
res += c.lower()
else:
res += c
return res
```
测试:
```python
print(camel_to_snake("helloWorld")) # hello_world
print(camel_to_snake("HelloWorld")) # hello_world
print(camel_to_snake("Hello_World")) # hello__world
```
注意点:
1. 如果字符串的第一个字符是大写字母,则转换后会在前面添加一个下划线。因此需要特判。
2. 如果字符串中已经有下划线,则转换后会出现连续的下划线。需要注意处理。
用ts语言将字符串从下划线式转换为驼峰式
下面是一个将字符串从下划线式转换为驼峰式的 TypeScript 函数:
```typescript
function toCamelCase(str: string): string {
return str.replace(/_([a-z])/g, (match, letter) => letter.toUpperCase());
}
```
该函数使用正则表达式将字符串中的下划线和下划线后面的字母替换为大写字母,从而使字符串变成驼峰式。例如:
```typescript
console.log(toCamelCase("hello_world")); // "helloWorld"
console.log(toCamelCase("my_name_is_john")); // "myNameIsJohn"
```