Write a Java Program?

2008-04-17 10:42 am
Write a Java Program with a static member call PrintOldChars that take in a String variable str. The function will print out all the characters of the string in odd position. For example:
PrintOddChars ("Hello World") will print out "HloWrd" in the screen.

回答 (3)

2008-04-17 11:06 am
✔ 最佳答案
Hey,it is very easy

public class PrintAltText {

public static void main(String[] args) {

String s="Hello World";
printAltString(s);
}


public static void printAltString(String text)
{
for(int i=0;i<text.length();i=i+2)
{

System.out.println(text.charAt(i));
}
}
}

The printAltString method will prints the odd characters of the string .

All the Best
2008-04-21 12:30 pm
Yes, using the String function charAt() is a good idea, but not an efficient one...because each time you perform a charAt() invocation, a new string is created on the heap. A better way to manipulate strings would be use char array as follows.

public class PrintAltChars {
public static void main(String[] args) {
String s = "YahooAnswers";
char[] c = s.toCharArray();
for(int i=0;i<c.length;i++) {
if(i%2==0) {
System.out.print(c[i]);
}
}
}
}

Enjoy!
參考: Past experience.
2008-04-17 5:46 pm
you must install java machine.type on searche java machine and install.kissssss


收錄日期: 2021-05-02 18:18:08
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20080417024226AARMVjN

檢視 Wayback Machine 備份