+ 5
How can i print result outside for loop ? What should i change in the code?
public static void main(String[] args) { String str ="muslim,pro,is,recognized,by,millions,of,islam,followers,around,the,world "; String[]ch=str.split(","); StringBuilder z =new StringBuilder(); for(String sstr : ch){ String c = sstr.substring(0,1).toUpperCase()+sstr.substring(1)+sstr.substring(sstr.length()-1).toUpperCase(); z.append(c); } System.out.print(z); } }
14 odpowiedzi
+ 3
Fatma hgazy
append string in StringBuilder with space
int l = sstr.length();
String c = sstr.substring(0, 1).toUpperCase() + sstr.substring(1, l - 1) + sstr.substring(l - 1).toUpperCase();
z.append(c + " ");
Then print z outside the loop
+ 2
c = .. follow your code
+ 1
It seems that you are overwriting z in every iteration. You need to declare an ArrayList of strings to store the words in every iteration.
+ 1
Declare this ArrayList outside the for loop.
ArrayList<String> words = new ArrayList<String>();
Then add this at the end of the for loop
words.add(c);
+ 1
You don't need the StringBuilder at all.
+ 1
public class Program {
public static void main(String[] args) {
String str ="muslim,pro,is,recognized,by,millions,of,islam,followers,around,the,world ";
String[]ch=str.split(",");
StringBuilder z =new StringBuilder();
for(String sstr : ch) {
String c = sstr.substring(0,1).toUpperCase()+sstr.substring(1)+sstr.substring(sstr.length()-1).toUpperCase();
z.append(c);
}
System.out.print(z);
}
}
0
You should declare StringBuilder z outside the for loop and just write z = new StringBuilder() inside the for loop.
0
Doesn't work
0
Can you write this 🥺
0
variables declared inside block (like loop) doesn't exist outside block
StringBuilder z = new StringBuilder();
for (String sstr : ch) {
String c =
0
String c equal what
0
Doesn't work
0
I want output like this
MusliM PrO IS RecognizeD BY MillionS OF IslaM FollowerS ArounD ThE WorlD
Ok
About space i will do like this at the end behind z like this
System.out.print(z+ " ");
But the problem now your code didn't output the same result
0
add
.append(" ");
after each word. append is the method of StringBuilder.
and sstr.substring(1) is wrong because you want to cut the last char
btw for effective code use append() instead all string concatenation by + here
//c =
z.append(..).append(..).append(..) ..
/first_char .middle .end_char