I am trying to get a program working which does the following:
Let's say we have a String
called name
, set to "Stack Overflow Exchange"
. I want to output to the user "SOE"
, with the first characters of each word. I tried with the split()
method, but I failed to do it.
My code:
public class q4 {
public static void main(String args[]) {
String x = "michele jones";
String[] myName = x.split("");
for(int i = 0; i < myName.length; i++) {
if(myName[i] == "") {
String s = myName[i];
System.out.println(s);
}
}
}
}
I am trying to detect if there are any spaces, then I can simply take the next index. Could anyone tell me what I am doing wrong?
String initials = "";
for (String s : fullname.split(" ")) {
initials+=s.charAt(0);
}
System.out.println(initials);
This works this way :
EDIT :
As suggested, string concatenation is often not efficient, and StringBuilder is a better alternative if you are working on very long strings :
StringBuilder initials = new StringBuilder();
for (String s : fullname.split(" ")) {
initials.append(s.charAt(0));
}
System.out.println(initials.toString());
EDIT :
You can obtain a String as an array of characters simply :
char[] characters = initials.toString().toCharArray();
Try splitting by " "
(space), then getting the charAt(0)
(first character) of each word and printing it like this:
public static void main(String args[]) {
String x = "Shojibur rahman";
String[] myName = x.split(" ");
for (int i = 0; i < myName.length; i++) {
String s = myName[i];
System.out.println(s.charAt(0));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With