[英]Printing only the first 5 characters of a string in one line
我試圖在一行中僅打印給定字符串的前5個字符。 我的問題是整個字符串沒有被打印。 結束部分被切斷。
int l = 0;
int m = 5;
for(int i = 0; i < (string.length()/5) ; i++)
{
System.out.println(string.substring(j,k));
l = m;
m = m + 5;
}
給定string = "Hello world, my name is something which you want to"
,結果將是這樣的:
Hello
worl
d, my
但是,字符串的最后部分沒有被打印。
但是,字符串的最后部分沒有被打印。
是的,沒錯-由於您的循環條件。 您正在迭代(string.length()/5)
次-四舍五入。 因此,如果字符串包含12個字符,則只需迭代兩次,就省去了最后兩個字母。
我建議解決這個問題略有不同-擺脫l
和m
變量(我假設您打算在substring
調用中使用-永遠不要聲明j
或k
),而應在for
循環中使用該變量。 但是,您需要確保不要嘗試在substring
末尾使用substring
字符串Math.min
對此非常方便:
for (int sectionStart = 0; sectionStart < string.length(); sectionStart += 5) {
int sectionEnd = Math.min(string.length(), sectionStart + 5);
System.out.println(string.substring(sectionStart, sectionEnd);
}
根據您的問題,我了解的是,您需要輸出
Hello
worl
d, my
name
is so
String str="Hello world, my name is something which you want to";
for(int i=0;i<str.length();i++)
{
if(i%5==0 && i!=0)
{
System.out.println("");
}
System.out.print(str.charAt(i));
}
再增加一種方法
String str="Hello world, my name is something which you want to";
for(int i=0,j=0;i<str.length();)
{
if(j<str.length() && (str.length()-j)>5)
{j=i+5;}
else
{j=str.length();}
System.out.println(str.substring(i,j));
i+=5;
}
輸出:
Hello
worl
d, my
name
is s
ometh
ing w
hich
you w
ant t
o
您的變量無處不在。 你有i
, j
, k
, l
, m
; 其中一些未在您提供的代碼中定義。
但是您應該只有一個:子串的開頭,說i
。 子字符串的結尾總是多5個: (i + 5)
。 然后每個循環將其增加5。
簡單的遞歸方法
void test(String t){
if(t.length() > 4){
String o = t.substring(0,5);
System.out.println(o);
String x = t.substring(5,t.length());
test(x);
}
else{
System.out.println(t);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.