【发布时间】:2022-07-08 00:12:22
【问题描述】:
我有一串随机地址,比如
String s="H.N.-13/1443 laal street near bharath Dental lab near thana qutubsher modern bakery saharanpur uttar pradesh 247001";
我想用两个条件将它拆分成字符串数组:
#该字符串数组的每个元素的长度小于或等于20。
#字符串数组的元素没有尴尬的结尾。例如:-
[
{H.N.-13/1443 laal st},
{reet near bharath de},
{thana 附近的国家实验室},
{qutubsher 靠近现代},
{n 面包店撒哈拉普尔}
]
正确的输出应该是 [
{H.N.-13/1443 拉尔},
{bharath 附近的街道},
{附近的牙科实验室},
{thana qutubsher 附近},
{现代面包店}
{撒哈拉普尔} ]
注意字符串数组中的每个元素如何小于或等于 20。
以上是我对这段代码的输出:
\\
static String[] split(String s,int max){
int total_lines = s.length () / 24;
if (s.length () % 24 != 0)
{
total_lines++;
}
String[] ans = new String[total_lines];
int count = 0;
int j = 0;
for (int i = 0; i < total_lines; i++)
{
for (j = 0; j < 20; j++)
{
if (ans[count] == null)
{
ans[count] = "";
}
if (count > 0)
{
if ((20 * count) + j < s.length ())
{
ans[count] += s.charAt (20 * count + j);
}
else
{
break;
}
}
else
{
ans[count] += s.charAt (j);
}
}
String a = "";
a += ans[count].charAt (0);
if (a.equals (" "))
{
ans[i] = ans[i].substring (0, 0) + "" + ans[i].substring (1);
}
System.out.println (ans[i]);
count++;
}
return ans;
}
public static void main (String[]args)
{
String add =
"H.N.-13/1663 laal street near bharath dental lab near thana qutubsher near modern bakery";
String city = "saharanpur";
String state = "uttar pradesh";
String zip = "247001";
String s = add + " " + city + " " + state + " " + zip;
String[]ans = split (s);
}
【问题讨论】:
标签: java arrays string algorithm data-structures