package exercise_9;
public class Exercise9_29 {
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.println("Please enter am array and its split:");
String s1 = input.next();
System.out.println("Input split:");
String s2 = input.next();
String[] result=split(s1, s2);
for (int i = 0; i < split(s1, s2).length; i++) {
if (result[i] != null) {
System.out.print(result[i]+" ");
}
}
}
public static String[] split(String s1, String s2) {
String[] result = new String[s1.length()];
int t = 0;
for (int i = 0; i < s1.length(); i++) {
for (int j = 0; j < s2.length(); j++) {
if (s1.charAt(i)==s2.charAt(j)) {
result[t++]=String.valueOf(s1.charAt(i));
}else if (s1.charAt(i)!=s2.charAt(j)) {
result[t]+=String.valueOf(s1.charAt(i));
}
}
}
return result;
}
}
要求自己寫一個String類裡面的split方法返回由分隔符分隔開的字符串同時返回分割符,例如輸入?dwqdwq#das? ?#
返回? dwqdwq # das ?
但是我的程序不輸出字符串只輸出分隔符,求解釋
幫你修改了下,有好幾個錯誤。因為我是C#,但是代碼你可以對照修改,調試通過。
public static string[] split(string s1, string s2)
{
string[] result = new string[s1.Length];
int t = 0;
for (int i = 0; i < s1.Length; i++)
{
for (int j = 0; j < s2.Length; j++)
{
if (s1[i] == s2[j])
{
result[++t] += s1[i].ToString();
t++; i++;
}
}
result[t] += s1[i].ToString();
}
return result;
}
string[] result = split("hello#world?hello#kitty", "#?");
foreach (string s in result)
Console.WriteLine(s);
輸出
hello
#
world
?
hello
#
kitty
Press any key to continue . . .