[java][実装]文字の配列をカンマ区切りで出力してみる
2006/07/25
2006/11/26
シナリオ:
いろいろ実装方法はあると思う。
すぐに思いつくものをあげてみました。
public class TestFor {
/**
* シナリオ:文字の配列をカンマ区切りで出力します。
*/
public static void main(String[] args) {
String[] strings = { "a", "b", "c", "d", "e", "f", "g", "h", "i" };
System.out.println(pattern1(strings));
System.out.println(pattern2(strings));
System.out.println(pattern3(strings));
System.out.println(pattern4(strings));
}
public static String pattern1(String[] strings) {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < strings.length; i++) {
buffer.append(strings[i] + ",");
}
buffer.deleteCharAt(buffer.length() - 1);
return new String(buffer);
}
public static String pattern2(String[] strings) {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < strings.length - 1; i++) {
buffer.append(strings[i] + ",");
}
buffer.append(strings[strings.length - 1]);
return new String(buffer);
}
public static String pattern3(String[] strings) {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < strings.length; i++) {
buffer.append(strings[i]);
if (i < (strings.length - 1))
buffer.append(",");
}
return new String(buffer);
}
public static String pattern4(String[] strings) {
StringBuffer buffer = new StringBuffer();
String[] strings2 = new String[strings.length];
for(int i=0;i<strings2.length;i++)strings2[i] = ",";
strings2[strings2.length - 1] ="";
for (int i = 0; i < strings.length; i++) {
buffer.append(strings[i]).append(strings2[i]);
}
return new String(buffer);
}
}
文字の配列をカンマ区切りで出力してください。
いろいろ実装方法はあると思う。
すぐに思いつくものをあげてみました。
public class TestFor {
/**
* シナリオ:文字の配列をカンマ区切りで出力します。
*/
public static void main(String[] args) {
String[] strings = { "a", "b", "c", "d", "e", "f", "g", "h", "i" };
System.out.println(pattern1(strings));
System.out.println(pattern2(strings));
System.out.println(pattern3(strings));
System.out.println(pattern4(strings));
}
public static String pattern1(String[] strings) {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < strings.length; i++) {
buffer.append(strings[i] + ",");
}
buffer.deleteCharAt(buffer.length() - 1);
return new String(buffer);
}
public static String pattern2(String[] strings) {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < strings.length - 1; i++) {
buffer.append(strings[i] + ",");
}
buffer.append(strings[strings.length - 1]);
return new String(buffer);
}
public static String pattern3(String[] strings) {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < strings.length; i++) {
buffer.append(strings[i]);
if (i < (strings.length - 1))
buffer.append(",");
}
return new String(buffer);
}
public static String pattern4(String[] strings) {
StringBuffer buffer = new StringBuffer();
String[] strings2 = new String[strings.length];
for(int i=0;i<strings2.length;i++)strings2[i] = ",";
strings2[strings2.length - 1] ="";
for (int i = 0; i < strings.length; i++) {
buffer.append(strings[i]).append(strings2[i]);
}
return new String(buffer);
}
}
: