快速问题,每次来自char数组的字符不是后续字符时,我都会尝试打印新行。例如,如果text [i]是'a'而text [i + 1]不是'b',那么printf(“\ n”);
I / O的示例是:
input: "abk123@XY"
output: ab
123
XY
现在的输出是:
\n
\n
\n
这是我现在的代码:
void printNext(const char *t){
//variable declerations
int i;
for(i = 0; t[i] != '\0'; i++){
if(t[i] != t[i + 1])//line in question, which isn't working
printf("\n");
else if(t[i] >= '0' && t[i] <= '9')
printf("%c",t[i]);
else if (t[i] >= 'A' && t[i] <= 'Z' )
printf("%c",t[i]);
else if(t[i] >= 'a' && t[i] <= 'z')
printf("%c",t[i]);
}//end for
}//end printNext
主要功能是:
#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void printNext(const char *);
int main(void){
const char t[40] = "abk123@XY";
printf("the original sequence of strings is: %s\n", text);
printf("new string is: \n");
printNext(t);
}
答案 0 :(得分:1)
从所有条件中删除其他内容。否则只检查'if'是否失败。但是你想要检查下一个条件,同时改变检查条件的顺序。
for(i = 0; t[i] != '\0'; i++){
if(t[i] >= '0' && t[i] <= '9' )
printf("%c",t[i]);
if (t[i] >= 'A' && t[i] <= 'Z' )
printf("%c",t[i]);
if(t[i] >= 'a' && t[i] <= 'z')
printf("%c",t[i]);
if(t[i] + 1 != t[i + 1])
printf("\n");
}//end for
主要变化
int main(){
const char t[80] = "abk123@XY";
printf("the original sequence of strings is: %s\n", t);
printf("new string is: \n");
printNext(t);
return 0;
}
答案 1 :(得分:1)
我建议喜欢这个
#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>
bool sameKindAndSeq(unsigned char a, unsigned char b){
if(!a || !b || a + 1 != b)
return false;
if(islower(a))
return islower(b);
if(isupper(a))
return isupper(b);
if(isdigit(a))
return isdigit(b);
return false;
}
void printNext(const char *t){
bool first = true;//flag of top of sequence of same kind
for(; *t; ++t){
if(first){
if(sameKindAndSeq(*t, t[1])){
putchar(*t);
first = false;
}
} else {
if(sameKindAndSeq(t[-1], *t)){
putchar(*t);
}
if(!sameKindAndSeq(*t, t[1])){
putchar('\n');
first = true;
}
}
}
}
int main(void){
printNext("abk123@XY");
}
答案 2 :(得分:0)
@ minigeek的答案稍微更具可读性:
void printNext(const char *t)
{
int i;
int isdigit(int);
int isupper(int);
int islower(int);
for(i = 0; t[i] != '\0'; i++){
if (isdigit(t[i]))
printf("%c",t[i]);
if (isupper(t[i]))
printf("%c",t[i]);
if(islower(t[i]))
printf("%c",t[i]);
if(t[i] + 1 != t[i + 1])
printf("\n");
}
}