![](/img/trans.png)
[英]Why does my C program print new blank lines when I try to print a string in the reverse order?
[英]C program to reverse a string with new lines
我無法修復此功能以逐行反轉文件中的單詞。 我不知道如何處理新行。 這不是學校的作業,我只是想自己解決這個問題,而且我已經做了一段時間了。 我認為 '\\n' 字符附加到單詞的末尾,算法沒有考慮到這一點,我不知道如何。 你會告訴我如何正確實施嗎?
void reverseWord (char* buffer, int size)
{
char* start = buffer;
// bounds
char* temp = buffer;
// Reversing the words
while (*temp) {
temp++;
if(*temp == '\n'){
temp++;
}
if (*temp == '\0') {
reverse(start, temp - 1);
}
else if (*temp == ' ') {
reverse(start, temp - 1);
start = temp + 1;
}
}
// Reverse the entire string
reverse(buffer, temp - 1);
}
void reverse(char* begin, char* end)
{
char temp;
while (begin < end) {
temp = *begin;
*begin++ = *end;
*end-- = temp;
}
}
我的輸入文件是:
this is line 1
this is line 2
this is line 3
this is line 4
this is line 5
我想要的輸出是:
5 line is this
4 line is this
3 line is this
2 line is this
1 line is this
我的實際輸出是這樣的:
5
line is this4
line is this3
line is this2
line is this1
先感謝您。
首先:如果您用像 C 這樣的“簡單”語言在這里發布問題,請提供一個最小的可重現示例,如@Yunnosch 所說。 它會讓你有更多的人嘗試你的代碼。
如果它像原始一樣就足夠了
int main() {
char buffer[] =
"this is line 1\n"
"this is line 2\n"
"this is line 3\n"
"this is line 4\n"
"this is line 5\n";
printf("%s", buffer);
reverseWord(buffer, strlen(buffer));
printf("%s", buffer);
}
順便說一句,我從您未修改的代碼中得到的輸出與您發布的有點不同:
5
line is 4
this line is 3
this line is 2
this line is 1
this line is this
好吧,現在到您的代碼。
你的while
循環永遠不會評估if (*temp == '\\0')
為true
因為它的條件會預先破壞循環。 但這不是原因。
您可以像查看任何其他空白字符一樣查看換行符。 所以我成功地嘗試了這個:
while (*temp) {
temp++;
if (isspace(*temp)) {
reverse(start, temp - 1);
start = temp + 1;
}
}
您需要為isspace()
#include <ctype.h>
。
它似乎甚至適用於像\\r\\n
這樣的 Windows 風格的換行符。 但是您應該非常仔細地調查換行符是否正確。 您可能想學習為此使用調試器。
我已經運行了你的代碼,我找到了一些對你有用的答案:
1) 如果您對reverseWord(..)
輸入是單行,例如“ this is line 1
”,那么您的輸出將是“ 1 line is this
”,這是完美的。 您現在可以做的只是為文件中的每一行調用該函數。
2)如果您對reverseWord(..)
輸入是文件中的整個文本,那么在reverseWord(..)
,您已經說過if(*temp =='\\n')...
只需寫相同的你為“ ”寫的東西。 這個:
If (*temp == '\n') {
reverse(start, temp-1);
start = temp + 1;
}
還!! 確保正確獲得尺寸。 在您的情況下,每行都是 15 個字符。 (包括'\\n'
和'\\0'
)
順便說一句,考慮將 '\\n' 與 ' ' 結合使用並使用 ||。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.