我想寫一個類似於PHP的str_repeat
的函數。我想要這個函數在字符串的末尾添加指定數量的字符。將char附加到字符串 - NXC語言
這是一個代碼,不工作(string argument 2 expected!
)
void chrrepeat(const char &ch, string &target, const int &count) {
for(int i=0; i<count; i++)
strcat(target, ch);
}
我想寫一個類似於PHP的str_repeat
的函數。我想要這個函數在字符串的末尾添加指定數量的字符。將char附加到字符串 - NXC語言
這是一個代碼,不工作(string argument 2 expected!
)
void chrrepeat(const char &ch, string &target, const int &count) {
for(int i=0; i<count; i++)
strcat(target, ch);
}
我不知道到底是什麼語言是(C++?),但你似乎是通過一個char strcat()
代替以空字符結尾的字符串。這是一個微妙的差異,但strcat
將愉快地訪問進一步無效的內存位置,直到找到空字節。
而不是使用strcat
,效率低下,因爲它總是搜索到字符串的末尾,您可以爲此自定義函數。
這裏是我實施C:
void chrrepeat(const char ch, char *target, int repeat) {
if (repeat == 0) {
*target = '\0';
return;
}
for (; *target; target++);
while (repeat--)
*target++ = ch;
*target = '\0';
}
我把它返回一個空字符串的情況下repeat == 0
因爲這是它如何工作的PHP,根據在線手冊。
此代碼假定目標字符串具有足夠的空間來重複發生。該函數的簽名應該是相當自我解釋,但這裏是一個使用它的一些示例代碼:
int main(void) {
char test[32] = "Hello, world";
chrrepeat('!', test, 7);
printf("%s\n", test);
return 0;
}
此打印:
Hello, world!!!!!!!
這是NXT Lego磚的「*不完全C *」語言。它有一種奇怪的字符串實現('string'不是'char *')。 –
但請不要刪除這個答案。它可能會幫助其他人通過google重定向到此處。 –
當然,我不會刪除它。我再也無法幫助你,我從來沒有聽說過這種語言。 –
將char轉換爲字符串。
void chrrepeat(char ch, string &target, const int count) {
string help = "x"; // x will be replaced
help[0] = ch;
for(int i=0; i<count; i++)
strcat(target, help);
}
你可以使用連接運算符嗎?例如:'target = target + ch' – shea