0

我想制作一个简单的程序来接受用户输入,并在每个字母之间放置空格。例如,用户进入商场,它返回商场(在同一行)。我正在尝试在其中创建一个带有 if 语句的循环。但我认为我需要 CharAt,所以如果字符串的值大于 1,我会为字符串中的每个单个字符声明一个变量(即用户输入) . 然后我会说在每个字母之间放置空格。我在AP计算机科学A,我们正在练习循环。这下的一切,都是我到目前为止所做的。方向在代码上面的注释中。我使用的是eclipse,java。

/**
 * Splits the string str into individual characters: Small becomes S m a l l
 */
public static String split(String str) {
    for (int i = 0; str.length() > i; i++) {
        if (str.length() > 0) {
            char space = str.charAt();
        }
    }
    return str;
}   
4

4 回答 4

2

我的解决方案用于concat构建str2, 并trim删除最后一个空格。

public static String split(String str) {
     String str2 = "";
     for(int i=0; i<str.length(); i++) {
        str2 = str2.concat(str.charAt(i)+" ");
     }
     return str2.trim();
}
于 2013-12-04T22:06:20.303 回答
1
  1. 您不修改方法参数,而是复制它们。
  2. 您不会在循环内进行空检查/空检查,而是在方法中首先执行此操作。
  3. a 中的标准for loopi < size,不是size > i……嗯

    /**
     * Splits the string str into individual characters: Small becomes S m a l l
     */
    public static String split(final String str) 
    {
        String result = "";
    
        // If parameter is null or empty, return an empty string
        if (str == null || str.isEmpty())
            return result;
    
        // Go through the parameter's characters, and modify the result
        for (int i = 0; i < str.length(); i++) 
        {
            // The new result will be the previous result,
            // plus the current character at position i,
            // plus a white space.
            result = result + str.charAt(i) + " ";  
        }
    
        return result;
    }   
    


4. Go pro,StringBuilder用于结果,静态最终常量用于空字符串和空格字符。

和平!

于 2013-12-04T21:58:18.280 回答
0

问自己一个问题,s来自哪里?

char space = s.charAt(); ??? s ???

第二个问题,性格在?

public static String split(String str){
    for(int i = 0; i < str.length(); i++) {
        if (str.length() > 0) {
            char space = str.charAt(i)
        }
    }
    return str;
}
于 2013-12-04T21:50:16.280 回答
0

@Babanfaraj,这是像你这样的新手的回答!!代码非常简单。更正后的程序是——

class fopl
{
    public static void main(String str) 
    {
    int n=str.length();
        for (int i = 0;i<n; i++) 
    {
        if (n>=0) 
        {
            String space = str.charAt(i)+" ";
            System.out.print(space);
        }
    }
}   
}

很高兴为您提供帮助!

于 2017-01-12T10:26:41.303 回答