c - 如何直接比较数组中的第一个和第二个元素?

标签 c arrays if-statement for-loop

快速问题,每次 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);


 }

最佳答案

从每个条件中删除 else。 else if 仅在 '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; 

}

关于c - 如何直接比较数组中的第一个和第二个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42777224/

相关文章:

ios - swift iOS : How to refactor a lot of conditions for if statement?

javascript - 将函数放入 return 语句中

c - 我的程序在比较数组中的元素时崩溃

c - C 中的结构(指针用法和显示关系)

java - 在java中生成唯一的随机数

c++ - 初学者 C++ 程序员,对动态数组感到困惑

macos - 使 2 个相互矛盾的方法在 drawRect 中起作用

c - GCC内联汇编中的 "=w"是什么意思?

c - C : Why do I have to explicitly reassign head and tail even when they are not changed? 中的双向链表

C# 3 维数组定义问题