我有一个使用tr翻译后的字符串,如何将它转为翻译前的呢?
时间: 2024-03-23 13:41:13 浏览: 18
如果你要将 `tr()` 函数翻译后的字符串转为翻译前的字符串,可以使用 `QObject::tr()` 函数的重载版本:
```cpp
QString QObject::tr(const char *sourceText, const char *disambiguation = nullptr, int n = -1)
```
该函数会返回翻译前的字符串。需要注意的是,该函数只能将 `tr()` 函数翻译后的字符串转为翻译前的字符串,如果传入的字符串不是 `tr()` 函数翻译后的字符串,则返回的结果可能不正确。
示例代码如下:
```cpp
QString translatedText = tr("Hello world!"); // 使用 tr() 函数翻译字符串
QString originalText = QObject::tr(qPrintable(translatedText)); // 将翻译后的字符串转为翻译前的字符串
qDebug() << originalText; // 输出结果为 "Hello world!"
```
其中,`qPrintable()` 函数用于将 `QString` 类型的字符串转为 `const char*` 类型的字符串。
相关问题
请将程序补充完整。编写一个字符翻译程序,将这个函数取名为 tr(), 它有三个字
符串参数: input_str, from_str, to_str。其中 input_str 为待翻译的字符串,from_str 为需要替换的字符集合,to_str 为替换后的字符集合。
以下是代码实现:
```python
def tr(input_str, from_str, to_str):
"""
字符串翻译函数
:param input_str: 待翻译的字符串
:param from_str: 需要替换的字符集合
:param to_str: 替换后的字符集合
:return: 翻译后的字符串
"""
# 构造翻译表
trans_table = str.maketrans(from_str, to_str)
# 调用 translate 方法进行翻译
return input_str.translate(trans_table)
```
使用示例:
```python
>>> tr('hello world', 'aeiou', '12345')
'h2ll4 w4rld'
```
请将程序补充完整。编写一个字符翻译程序,将这个函数取名为 tr(),它有三个字
符串参数:源字符串、待替换字符、替换字符。函数功能为将源字符串中的待替换字符替换为替换字符并返回替换后的字符串。
以下是程序示例:
```python
def tr(src_str, old_char, new_char):
"""
字符翻译程序
:param src_str: 源字符串
:param old_char: 待替换字符
:param new_char: 替换字符
:return: 替换后的字符串
"""
# 将源字符串拆分为单个字符列表
char_list = list(src_str)
# 遍历单个字符列表,对待替换字符进行替换
for i in range(len(char_list)):
if char_list[i] == old_char:
char_list[i] = new_char
# 将字符列表转换为字符串并返回
return ''.join(char_list)
```
使用示例:
```python
src_str = "hello world"
old_char = "o"
new_char = "a"
result_str = tr(src_str, old_char, new_char)
print(result_str) # 输出: "hella warld"
```