如何读取用户输入字符串并按格式输出单个字符?附Java代码
Solution for Formatting String Characters with Commas and Multi-Space Word Separators
Got it, let's fix up your code to meet the requirement: splitting each character with commas, and using multiple spaces (or as shown in your example) between words. Here's the complete, working implementation with explanations:
Complete Java Code
import java.util.Scanner; public class A { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter any String:"); String name = sc.nextLine(); System.out.println("Before Splited: " + name); // Use StringBuilder for efficient string concatenation StringBuilder formattedResult = new StringBuilder(); for (int i = 0; i < name.length(); i++) { char currentChar = name.charAt(i); if (currentChar == ' ') { // Add two non-breaking spaces (matches your example's ) formattedResult.append(" "); } else { // Convert to lowercase to match your example's output (remove if not needed) formattedResult.append(Character.toLowerCase(currentChar)); // Only add comma if it's not the last character, and next char isn't a space if (i != name.length() - 1 && name.charAt(i + 1) != ' ') { formattedResult.append(","); } } } System.out.println("After Formatted: " + formattedResult); sc.close(); } }
Key Logic Breakdown
- Efficient String Building: We use
StringBuilderinstead of repeatedStringconcatenation because it's faster and uses less memory, especially for longer strings. - Word Separation Handling: When we hit a space (word boundary), we append two
(if you need console output instead of HTML, replace this with two regular spaces). - Character & Comma Placement:
- Each non-space character is converted to lowercase (to match your example's
j,a,v,ainstead ofJ,a,v,a— removeCharacter.toLowerCase()if you want to keep original case). - We only add a comma if:
- It's not the very last character in the string.
- The next character isn't a space (so we don't add a comma right before a word separator).
- Each non-space character is converted to lowercase (to match your example's
Example Test Run
If you input:
Java is one of the most popular language
The output will be:
j,a,v,a i,s o,n,e o,f t,h,e m,o,s,t p,o,p,u,l,a,r l,a,n,g,u,a,g,e
Quick Adjustments
- Keep original character case: Remove
Character.toLowerCase()from the code. - Console-friendly spacing: Replace
" "with" "(two regular spaces).
内容的提问来源于stack exchange,提问作者Amit Singh
相关产品推荐
相关产品推荐

