CharAt的麻烦

时间:2013-12-04 21:45:58

标签: java string charat

我想制作一个简单的程序来接受用户输入,并在每个单个字母之间放置空格。例如,用户输入mall,它返回M A L L(在同一行上)。 我试图在其中创建一个带有if语句的循环。但我认为我需要CharAt,所以如果字符串的值大于1,我会在字符串中声明一个变量为everysingle字符(即userinput) 。然后我会说在每个字母之间加上空格。我在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 个答案:

答案 0 :(得分: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();
}

答案 1 :(得分:1)

  1. 您不修改方法参数,而是复制它们。
  2. 你不在循环中进行空检查/清空检查,你首先在方法中做。
  3. for loop中的标准为i < size,而不是size > i ... meh

    /**
     * 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. <小时/> 4.转到专业版,使用StringBuilder作为结果,使用静态最终常量作为空字符串和空格字符。

    和平!

答案 2 :(得分: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;
}

答案 3 :(得分:0)

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

FileInputFormat.setInputPath(job, new Path(inputFile));

很高兴为您服务!