我需要在方形星形圖案的框架內列印居中的字串。
例子:
const char tekst[]="這是 C 中字串編程的示例"; 整數寬度 = 20; 輸出:
********************
* This is example *
* of string progr- *
* amming in C *
********************
如果需要添加的空格數為奇數,則應在右側添加多余的空格。如果整個單詞無法放入該行,則添加破折號并在下一行繼續單詞。不允許使用輔助字串。代碼:
#include <stdio.h>
#include <string.h>
void framed(const char *tekst, int width) {
int i, j = 0, count = 0;
for (i = 0; i < width; i )
printf("*");
printf("\n");
while (tekst[j] != '\0') {
count ;
if (count == 1)
printf("* ");
printf("%c", tekst[j]);
j ;
if (count 5 > width) {
printf(" *");
printf("\n");
count = 0;
}
if (j == strlen(tekst))
for (i = 0; i < width - count; i )
printf(" ");
}
printf("*\n");
for (i = 0; i < width; i )
printf("*");
}
int main() {
const char tekst[] = "This is example of string programming in C";
int width = 20;
framed(tekst, width);
return 0;
}
這是我的輸出:
********************
* This is example *
* of string progra *
* mming in C *
********************
你能幫我修復我的代碼以獲得正確的輸出嗎?
uj5u.com熱心網友回復:
在這里,您將附加字符"* "" *"考慮在內(因為 有一點偏差>):
if (count 5 > width)
在這里你不會:
for (i = 0; i < width - count; i )
如果您確實將它們考慮在內,它(框架)就可以作業。
for (i = 0; i <= width - (count 5); i )
假設您稍后也始終如一地輸出
printf(" *\n");
我建議用較少的附加字符數來替換非常神奇的數字 5;4 for "* *"and 適應條件<=and >。
所需輸出的其他差異(居中而不是左對齊和正確插入“-”)甚至沒有被顯示的代碼嘗試過,所以我假設它們不是所詢問的內容的一部分。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/436148.html
