排序后带有“%s”丢失字符的 printf 字符串
printf string with "%s" loss character after sort
这是一个简单的排序代码:
#include <stdio.h>
int main(void) {
int i, j;
char str[] = "Hello!! How are you?? I'm Fine. No Thank you.", temp;
for (i = 0; i < sizeof(str); i++) {
for (j = i + 1; j < sizeof(str); j++) {
if (str[i] > str[j]) {
temp = str[j];
str[j] = str[i];
str[i] = temp;
}
}
}
for(i = 0; i < sizeof(str); i++)
printf("%c", str[i]);
printf("%s", str);
}
我发现我可以通过 for
循环逐字符打印排序后的字符串,但不能 printf("%s", str);
,它不会打印任何东西,谁能告诉我为什么以及如何解决这个问题?
您可以使用strlen
函数来计算字符串的长度。
#include <stdio.h>
#include <string.h>
int main(void) {
int i, j;
char str[] = "Hello!! How are you?? I'm Fine. No Thank you.", temp;
int n = strlen(str);
for(i=0; i<n; i++){
for(j=i+1; j<n; j++){
if(str[i]>str[j]){
temp = str[j];
str[j]=str[i];
str[i]=temp;
}
}
}
for(i=0; i<n; i++) printf("%c",str[i]);
printf("%s", str);
}
您将字符串的大小计算为 sizeof(str)
。这包括尾随 [=12=]
。字节 [=12=]
保证在排序字符串的开头结束,告诉 printf
该字符串实际上是空的。您希望将终止 NUL 保留在字符串末尾之后,因为它不是您要排序的缓冲区的一部分。
要仅对字符串的字符进行排序,不带终止符,将循环更改为
int n = strlen(str);
for(i = 0; i < n; i++) {
for(j = i + 1; j < n; j++) {
这是一个简单的排序代码:
#include <stdio.h>
int main(void) {
int i, j;
char str[] = "Hello!! How are you?? I'm Fine. No Thank you.", temp;
for (i = 0; i < sizeof(str); i++) {
for (j = i + 1; j < sizeof(str); j++) {
if (str[i] > str[j]) {
temp = str[j];
str[j] = str[i];
str[i] = temp;
}
}
}
for(i = 0; i < sizeof(str); i++)
printf("%c", str[i]);
printf("%s", str);
}
我发现我可以通过 for
循环逐字符打印排序后的字符串,但不能 printf("%s", str);
,它不会打印任何东西,谁能告诉我为什么以及如何解决这个问题?
您可以使用strlen
函数来计算字符串的长度。
#include <stdio.h>
#include <string.h>
int main(void) {
int i, j;
char str[] = "Hello!! How are you?? I'm Fine. No Thank you.", temp;
int n = strlen(str);
for(i=0; i<n; i++){
for(j=i+1; j<n; j++){
if(str[i]>str[j]){
temp = str[j];
str[j]=str[i];
str[i]=temp;
}
}
}
for(i=0; i<n; i++) printf("%c",str[i]);
printf("%s", str);
}
您将字符串的大小计算为 sizeof(str)
。这包括尾随 [=12=]
。字节 [=12=]
保证在排序字符串的开头结束,告诉 printf
该字符串实际上是空的。您希望将终止 NUL 保留在字符串末尾之后,因为它不是您要排序的缓冲区的一部分。
要仅对字符串的字符进行排序,不带终止符,将循环更改为
int n = strlen(str);
for(i = 0; i < n; i++) {
for(j = i + 1; j < n; j++) {