簡體   English   中英

如何在Java中打印字符串數組的偶數和奇數位置字符?

[英]How to print even and odd position characters of an array of strings in Java?

給定一個長度為 N 的字符串 S,索引從 0 到 N-1,將它的偶數索引和奇數索引字符打印為 2 個空格分隔的字符串在一行上。 假設輸入從索引位置 0 開始(被認為是偶數)

輸入

第一行包含一個整數 T(測試用例的數量)。 后續 T 行中的每一行 i 都包含一個字符串 S。

輸出

對於每個字符串 S,打印它的偶數索引字符,然后是空格,然后是奇數索引字符。

樣本輸入

2

黑客

排名

樣本輸出

阿克爾

納克

我寫的代碼

public static void main(String[] args)
{
    Scanner scan    =   new Scanner(System.in);
    int T   =   scan.nextInt();
    scan.nextLine();

    for(int i=0 ; i<T ; i++)
    {
        String  myString    =   scan.nextLine();

        int evn =   0,
            odd =   0,
            len =   myString.length();

        char    strE[]  =   new char[50],
                strO[]  =   new char[50];

        for(int j=0 ; j<len ; j++)
        {
            if(j%2 == 0)
            {
                strE[evn]   =   myString.charAt(j);
                evn++;
            }
            if(j%2 == 1)
            {
                strO[odd]   =   myString.charAt(j);
                odd++;
            }
        }
        System.out.print(strE);
        System.out.print(" ");
        System.out.println(strO);
    }
}

我的輸出

阿克爾

納克

問題

如您所見,我的程序成功滿足測試用例和其他測試用例(使用自定義輸入)但每次 HackerRank 編譯器告訴我我的程序不滿足測試用例。

顯然,我的程序正在生成所需的輸出,但是每次 HackerRank 編譯器告訴我我的解決方案是錯誤的。

誰能告訴我我在哪里犯了錯誤?

進一步修改

然后我決定將打印語句的最后 3 行更改為一個語句,如下所示:

System.out.println(strE + " " + strO);

但是,這次程序沒有產生所需的輸出,而是打印了一些垃圾值,如下所示:

[C@5c3f3b9b [C@3b626c6d

[C@3abc8690 [C@2f267610

我的疑惑

1. 在第一種情況下,當我使用 2 個打印語句分別打印兩個字符串時,我每次都得到正確的輸出,但 HackerRank 編譯器拒絕了它。 為什么?

2. 在第二種情況下,當我通過使用一個打印語句而不是 3 個打印語句來修改程序以獲得所需的結果時,該程序給出了完全不同的輸出和打印的垃圾值! 為什么?

以下是 HackerRank 問題的鏈接以獲取更多信息: hackerrank.com/challenges/30-review-loop

非常感謝所有幫助和指導,並在此先感謝!

嘗試提交這個:

Scanner scan = new Scanner(System.in);
int T = scan.nextInt();
scan.nextLine();
for (int i = 0; i < T; i++) {
    String myString = scan.nextLine();
    String even = "";
    String odd = "";
    for (int j = 0; j < myString.length(); j++) {
        if (j % 2 == 0) {
            even += myString.charAt(j);
        } else {
            odd += myString.charAt(j);
        }
    }

    System.out.println(even + " " + odd);
}

我得到了正確的輸出,它應該滿足所有要求。 我認為你的代碼失敗了,因為它不是你最后打印的真正字符串,而且你的數組中有空點

    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter the no.of test-cases:");
    int t = scanner.nextInt();
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter the String(s)");
    for (int i = 0; i < t; i++) {

        String myString = br.readLine();
        String even = "";
        String odd = "";
        for (int j = 0; j < myString.length(); j++) {
            if (j % 2 == 0) {
                even += myString.charAt(j);
            } else {
                odd += myString.charAt(j);
            }
        }
        System.out.println(even);
        System.out.println(odd);
    }
    scanner.close();

我可以解決你的第二個問題:---> System.out.print(strE);-->在底部,方法被調用(public void print(char s[]));

-->System.out.println(strE + " " + strO);-->在底部調用方法(public void println(String x))

對於您的第一個答案,我無法回答您,因為我不知道編譯器的工作原理,但我可以回答您的第二個問題。

System.out.print(strE); System.out.print(" "); System.out.println(strO);的原因System.out.print(strE); System.out.print(" "); System.out.println(strO); 有效是因為System.out.print(char[])System.out.println(char[])在打印之前自動將字符數組轉換為可讀字符串。

然而,在第二種情況下System.out.println(strE + " " + strO); ,你所做的是直接將char數組轉成字符串,它只是打印數組對象的類和哈希碼,因為toString()方法在數組類中沒有被覆蓋。 你想要做的是System.out.println(new String(strE) + " " + new String(strO)); . 它會給你你想要的結果。

int T = scan.nextInt();

這會讀取我們將要處理的測試用例的數量。

String string[] = new String[T];
for(int i = 0; i<T; i++){
  string[i] = scan.next();

接下來,我們將創建一個名為“string”的數組(順便說一句,這是變量/對象的錯誤名稱),其大小為 T,並且在 for 循環中從輸入 T 次讀取測試用例並將它們保存在數組中。

for(int temp = 0; temp<T; temp++){

現在,對於每個測試用例,我們執行以下操作...

for(int j = 0; j<string[temp].length(); j = j+2)
{
    System.out.print(string[temp].charAt(j));
}

我們創建了一個局部變量 j,它只在這個 for 循環中可見。 j 保存我們正在處理的字符串 (=string[temp]) 的索引。 所以,我們在位置 j 打印一個字符(通過使用 String 類的標准方法“charAt”,它返回字符串給定索引的字符),然后將其增加 2。因此,此代碼將打印每個偶數字符。 對於字符串“example”,它將打印“eape”(j=0, j=2, j=4, j=6)。

System.out.print(" ");

用空格分隔序列。

for(int j = 1; j<string[temp].length(); j = j+2){
    System.out.print(string[temp].charAt(j));
}

System.out.println();

我們正在做同樣的事情(創建索引 j,運行字符串的所有字符),但是從“1”開始,所以它將打印字符串的所有奇數字符。 對於字符串“example”,它會給你“xml”(j=1, j=3, j=5)。 在此之后,它將結束字符串。 我希望,它會幫助你理解。 :)

import java.io.*;
import java.util.*;

public class Solution {

 private static void f(String s) {
 // TODO Auto-generated method stub
  char c[]=s.toCharArray();
  int i,j;
  for (i = 0; i <c.length;i++){ 
      System.out.print(c[i]);
      i+=1;
  }
  System.out.print(" ");
  for (j = 1; j<c.length;j++){
     System.out.print(c[j]);
     j+=1;    
  }
 }
 public static void main(String[] args){
    // TODO Auto-generated method stub
    Scanner sc=new Scanner(System.in);
    int s=sc.nextInt();
    while(hasNext()){
    //for loop for multiple strings as per the input
        for(int m=0;m<= s;m++){    
          String s1=sc.next();
          f(s1); 
          System.out.println();
        }
     }
   }
}

我已經通過兩種方式解決了這個問題,並且都產生了正確的輸出。

看一看,如果您有任何問題,請告訴我。

  1. 您可以使用 String,而不是使用 char 數組

     //char[] even = new char[10000]; String even = "";

我們看一下代碼

private static Scanner scanner = new Scanner(System.in); 

public static void main(String[] args) {

        String s = scanner.next();

        char[] array = s.toCharArray();

        int count=0;            
        //char[] even = new char[10000];
        //char[] odd = new char[10000];
        String even = "";
        String odd = "";
        for(char ch : array){

            if(count%2 == 0){
                even = even + ch;
            }else{
                odd = odd + ch;
            }
            count++;
        }
        count = 0;

        System.out.println(even + " " + odd);
}

輸出:

  hacker
  hce akr
  1. 不需要額外的 char[] 或 String 來存儲偶數和奇數位置的字符,我們可以使用適當的條件直接打印它們。

     private static Scanner scanner = new Scanner(System.in); public static void main(String[] args){ String s = scanner.next(); char[] array = s.toCharArray(); int count=0; for(char ch : array){ if(count%2 == 0){ System.out.print(ch); } count++; } count = 0; System.out.print(" "); for(char ch : array){ if(count%2 != 0){ System.out.print(ch); } count++; } count = 0; }

輸出:

  hacker
  hce akr

嘗試這個:

public static void main(String[] args) {
    System.out.println("Enter string to check:");
    Scanner scan = new Scanner(System.in);
    String T = scan.nextLine();
    String even = "";
    String odd = "";
    for (int j = 0; j < T.length(); j++) {
        if (j % 2 == 0) { //check the position of the alphabet by dividing it by 0
            even += T.charAt(j);
        } else {
            odd += T.charAt(j);
        }
    }
    System.out.println(even + " " + odd);

    scan.close();
}
** JavaScript version **

function processData(input) {
   for (let i = 1; i < input.length; i++) {
     printOutput(input[i]);
   }
}

function printOutput(input) {
  var result = [];
  input.length % 2 == 0 ? result[input.length / 2] = ' ': result[Math.ceil(input.length / 2)] = ' ';
  for (let i = 0; i < input.length; i++) {
    if (i % 2 == 0) {
        result[i / 2] = input[i];
    }
    else {
        result[Math.ceil(input.length / 2) + Math.ceil(i / 2)] = input[i];
    }
}
console.log(result.join(''));
}

process.stdin.on("end", function () {
processData(_input.split('\n'));

});
import java.io. * ;
import java.util. * ;

public class Solution {
String myString;
public Solution(String myString) {
    this.myString = myString;
    int len = myString.length();
    for (int j = 0; j < len; j++) {
        if (j % 2 == 0) {
            System.out.print(myString.charAt(j));
        }
    }
    System.out.print(" ");
    for (int j = 0; j < len; j++) {

        if (j % 2 == 1) {
            System.out.print(myString.charAt(j));
        }
    }
}
public static void main(String[] args) {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
    Scanner sc = new Scanner(System. in );
    int T = sc.nextInt();
    for (int i = 0; i < T; i++) {
        String word = sc.next();
        Solution sol = new Solution(word);
        System.out.println();
    }
    sc.close();
}

}

import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
       Scanner s = new Scanner(System.in);
        int T;
        T = s.nextInt();
        String[] str = new String[T];
        int i;
        for(i=0;i<T;i++) {
            str[i] = s.next();
        }    
        for(i=0;i<T;i++) {
            char[] even = new char[5000];
            char[] odd = new char[5000];
            int ev =0,od=0;
            for(int j= 0;j< str[i].length();j++) {
                if(j%2== 0) {
                    even[ev] = str[i].charAt(j);
                    ev++;
                }else {
                    odd[od] = str[i].charAt(j);
                    od++;
                }
            }
            String strEven = new String(even);
            String strOdd = new String(odd);
           System.out.print(strEven.trim());
           System.out.print(" ");
           System.out.println(strOdd.trim());

        }
        s.close();
    }
}

我相信這會起作用您忘記將其轉換為字符串並增加字符數組的大小

import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        Scanner scan= new Scanner(System.in);
        int n= scan.nextInt();
        for(int i=0;i<n;i++){
            String s= scan.next();
            int len= s.length();
            StringBuffer str_e= new StringBuffer();
            StringBuffer str_o= new StringBuffer();
            for(int j=0;j<len;j++){
                if(j%2==0)
                    str_e= str_e.append(s.charAt(j));
                if(j%2==1)
                    str_o= str_o.append(s.charAt(j));
            }
            System.out.println(str_e+" "+str_o);
        }
    }
}

嘗試這個:

import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        Scanner pp=new Scanner(System.in);
        int n=pp.nextInt();

        for(int i=0; i<n; i++)
        {
            String ip=pp.next();
            String re1="",
                    re2="";
            for(int j=0; j<ip.length(); j++)
            {
                if(j%2 == 0)
                {
                    re1+= ip.charAt(j);
                }
                if(j%2 == 1)
                {
                    re2+= ip.charAt(j);        
                }
            }
              System.out.print(re1+" "+re2);     
            System.out.println("");    
        }
    }
}
public class PrintCharacters{

public static void main(String args[]) {
    Scanner sc = new Scanner(System.in);
    
    int noOfTestCases = sc.nextInt();
    sc.nextLine();
    String []inputStrings= new String[noOfTestCases];
    for(int i=0;i<noOfTestCases;i++) {
        inputStrings[i]=sc.nextLine();
    }
    
    for(String str: inputStrings) {
        String even ="";
        String odd ="";
        for(int i=0;i<str.length();i++) {
            if(i%2==0) {
                even+=str.charAt(i);
            }else {
                odd+=str.charAt(i);
            }
        }
        System.out.println(even+" "+odd);
    }
    sc.close();
    
}

}


Input: 
  2
  Hacker
  Rank

Output:
  Hce akr
  Rn ak

導入 java.util.*;

公共課解決方案{

public static void main(String[] args) {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
    
    Scanner scan=new Scanner(System.in);
    int n=scan.nextInt();
    while(n>0) {
        String str=scan.next();
        for(int i=0;i<str.length();i++) {
            if(i%2==0) {
                System.out.print(str.charAt(i));
            }
        }
        System.out.print(" ");
        for(int i=0;i<str.length();i++) {
            if(i%2==1) {
                System.out.print(str.charAt(i));
            }
        }
        n--;
        System.out.println();
    }
    
    
}

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM