简体   繁体   English

在字符串中分别打印偶数个奇数字符

[英]print even odd characters separately in a string

Here is my code what I have tried, 这是我尝试过的代码,

I have to take a string from the user and as output i have to print the characters at even places and at odd places separated by a space 我必须从用户处获取一个字符串,并作为输出,我必须在偶数位置和奇数位置打印字符,并用空格隔开

MY PROBLEM: In every test case i am assigning to both the strings at end a null character to conclude that my string has ended. 我的问题:在每个测试用例中,我都为结尾处的两个字符串分配一个空字符,以得出我的字符串已结束的结论。 Lets suppose i enter 2 test cases and now if enter a smaller string than first test case in result it is printing my character of 2nd test case but also printing the characters of test case because first string was larger than second 假设我输入了2个测试用例,现在如果输入比第一个测试用例小的字符串,结果是打印我的第二个测试用例的字符,但同时打印测试用例的字符,因为第一个字符串大于第二个字符串

I want to ask how it can be possible if i have ended the string with a null character in every test case? 我想问一下,如果在每个测试用例中以空字符结尾的字符串怎么办?

so why it is printing the value after the null character because that were the characters of previous test case because that string was larger and its character are still there in array but it should print till null character Please help me to achieve this. 那么为什么要在空字符之后打印值,因为那是先前测试用例的字符,因为该字符串较大并且其字符仍在数组中,但是它应该打印直到空字符,请帮助我实现这一点。

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() {
   int t,i,j,k;
   scanf("%d ",&t);
   while(t>0){
       char s[10000],s1[10000],s2[100000];
      scanf("%s",s);
       for( i=0,j=0,k=0;i<strlen(s);i++){
           if(i%2==0)
               s1[j++]=s[i];
           else
                s2[k++]=s[i];


       }
       s1[strlen(s1)]='\0';
       s2[strlen(s2)]='\0';
       printf("%s %s\n",s1,s2);
       t--;

   }
}
   s1[strlen(s1)]='\0';
   s2[strlen(s2)]='\0';

This line is erroneous. 这条线是错误的。 Replace it with 替换为

   s1[j]='\0';
   s2[k]='\0';

This is because strlen() only works with checking null in a null terminated string. 这是因为strlen()只检查工作nullnull结束的字符串。 And at this point your generated string is not yet null terminated. 而在这一点您生成的字符串是没有null终止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM