[英]C++ equivalent of python's expandtabs() function?
我需要實現與 expandtabs() function 等效的 C++。 有人可以幫我將此代碼轉換為 C++ 嗎?
def expandtabs(string, n):
result = ""
pos = 0
for char in string:
if char == "\t":
# instead of the tab character, append the
# number of spaces to the next tab stop
char = " " * (n - pos % n)
pos = 0
elif char == "\n":
pos = 0
else:
pos += 1
result += char
return result
這就是我所擁有的:
std::string ExpandTabs(const std::string &str, int tabsize =4){
std::string ReturnString = str;
std::string result = " ";
int pos = 0;
for(std::string::size_type i = 0; i < ReturnString.size(); ++i) {
if (ReturnString[i] == '\t'){
int spaces = tabsize - pos % tabsize ;
ReturnString.append(" ", spaces);
pos = 0;
}
else{
pos+=1;
}
}
return ReturnString;
您需要逐個字符地構建字符串。 目前,您在 function 的開頭將str
分配給ReturnString
,然后將 append 分配給您決定字符串末尾所需的任何空格,而不是代替制表符。
毫無疑問,有更多慣用的方法可以實現相同的結果,但 python 的類似轉換可能看起來像。
#include <iostream>
#include <string>
std::string expand_tabs(const std::string &str, int tabsize=4)
{
std::string result = "";
int pos = 0;
for(char c: str)
{
if(c == '\t')
{
// append the spaces here.
result.append(tabsize - pos % tabsize, ' ');
pos = 0;
} else
{
result += c;
pos = (c == '\n') ? 0: pos + 1;
}
}
return result;
}
int main()
{
std::cout << expand_tabs("i\tam\ta\tstring\twith\ttabs") << '\n';
std::cout << expand_tabs("1\t2\t3\t4", 2) << '\n';
}
它基本上逐步將任何非制表符字符的輸入轉發到結果字符串,否則它會在結果中添加正確數量的空格。
Output:
i am a string with tabs
1 2 3 4
python 代碼的直接翻譯是有問題的,因為char
不能既是字符串又是單個字符,但除此之外它很簡單:
std::string expandtabs(std::string const&str, std::string::size_type tabsize=8)
{
std::string result;
std::string::size_type pos = 0
result.reserve(str.size()); // avoid re-allocations in case there are no tabs
for(c : str)
switch(c) {
default:
result += c;
++pos;
break;
case '\n':
result += c;
pos = 0;
break;
case '\t':
result.append(tabsize - pos % tabsize,' ');
pos = 0;
}
return result
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.