简体   繁体   English

在特定位置向字符数组添加内容 (Java)

[英]Add Something to Char Array at Specific Spot (Java)

I am tasked with taking a user sentence then separating it at the upper case letters as well as making those letters lower case after adding a " " .我的任务是获取一个用户句子,然后将其以大写字母分隔,并在添加" "后将这些字母变为小写。
I want to add a space add that position so that if user inputs "HappyDaysToCome" will output "Happy days to come" .我想添加一个空格添加该位置,以便如果用户输入"HappyDaysToCome"将输出"Happy days to come"

Current code当前代码

  public static void main(String[] args)
  {
    Scanner s = new Scanner(System.in);
    System.out.println("Please enter a sentence");
    String sentenceString = s.nextLine();
    char[] sentenceArray = sentenceString.toCharArray();
    for(int i = 0; i < sentenceArray.length; i++)
    {
        if(i!=0 && Character.isUpperCase(sentenceArray[i]))
        {
            Character.toLowerCase(sentenceArray[i]); 
            sentenceArray.add(i, ' ');    
        }

    }
    System.out.println(sentenceArray)
    s.close();
  }
}

There is no add method for arrays.数组没有add方法。 Arrays are not resizeable.数组不可调整大小。 If you indeed want to use a char[] array, you need to allocate one that is large enough, eg by counting the uppercase letters or simply by allocating a array that is surely large enough (twice the String length minus 1).如果您确实想使用char[]数组,则需要分配一个足够大的数组,例如通过计算大写字母或简单地分配一个足够大的数组( String长度减 1 的两倍)。

String input = ...

String outputString;

if (input.isEmpty()) {
    outputString = "";
} else {
    char[] output = new char[input.length() * 2 - 1];
    output[0] = input.charAt(0);
    int outputIndex = 1;
    for (int i = 1; i < input.length(); i++, outputIndex++) {
        char c = input.charAt(i);
        if (Character.isUpperCase(c)) {
            output[outputIndex++] = ' ';
            output[outputIndex] = Character.toLowerCase(c);
        } else {
            output[outputIndex] = c;
        }
    }
    outputString = new String(output, 0, outputIndex);
}

System.out.println(outputString);

Or better still use a StringBuilder或者最好还是使用StringBuilder

String input = ...

String outputString;

if (input.isEmpty()) {
    outputString = "";
} else {
    StringBuilder sb = new StringBuilder().append(input.charAt(0));

    for (int i = 1; i < input.length(); i++) {
        char c = input.charAt(i);
        if (Character.isUpperCase(c)) {
            sb.append(' ').append(Character.toLowerCase(c));
        } else {
            sb.append(c);
        }
    }
    outputString = sb.toString();
}

System.out.println(outputString);

You're approaching this the wrong way.你以错误的方式接近这个。 Just add each char back to a new string but with spaces included at the right spots.只需将每个字符添加回一个新字符串,但在正确的位置包含空格。 Don't worry about modifying your char array at all.根本不用担心修改你的字符数组。 Here is a slight modification of your code:这是对您的代码的轻微修改:

  public static void main(String[] args)
  {
    Scanner s = new Scanner(System.in);
    System.out.println("Please enter a sentence");
    String sentenceString = s.nextLine();
    char[] sentenceArray = sentenceString.toCharArray();

    //new string to hold the output
    //starts with only the first char of the old string
    string spacedString = sentenceArray[0] + "";

    for(int i = 1; i < sentenceArray.length; i++)
    {
      if(Character.isUpperCase(sentenceArray[i]))
      {
        //if we find an upper case char, add a space and the lower case of that char
        spacedString = spacedString + " " + Character.toLowerCase(sentenceArray[i]);    
      }else {
        //otherwise just add the char itself
        spacedString = spacedString + sentenceArray[i];
      }
    }

    System.out.println(spacedString)
    s.close();
  }

If you want to optimize performance, you can use a StringBuilder object.如果要优化性能,可以使用StringBuilder对象。 However, for spacing out a single sentence, performance isn't going to make any real difference at all.但是,对于单个句子的间隔,性能根本不会产生任何真正的区别。 If performance does matter to you, read more on StringBuilder here: https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html如果性能对您很重要,请在此处阅读有关StringBuilder更多信息: https : //docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html

We basically want to tokenize the input string on uppercase letters.我们基本上想用大写字母标记输入字符串。 This can be done using the regular expression [AZ][^AZ]* (ie, one uppercase, followed by zero or more "not" uppercase).这可以使用正则表达式[AZ][^AZ]* (即,一个大写,后跟零个或多个“非”大写)。 The String class has a built-in split() method that takes a regular expression. String类具有采用正则表达式的内置split()方法。 Unfortunately, you also want to keep the delimiter (which is the uppercase letter), so that slightly complicates matters, but it can still be done using Pattern and Matcher to put the matched delimiter back into the string:不幸的是,您还想保留定界符(大写字母),这样会使事情稍微复杂化,但仍然可以使用PatternMatcher将匹配的定界符放回字符串中:

import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.List;
import java.util.ArrayList;
public class Foo {
  public static void main(String[] args) {
    String text = "ThisIsATest1234ABC";
    String regex = "\\p{javaUpperCase}[^\\p{javaUpperCase}]*";
    Matcher matcher = Pattern.compile(regex).matcher(text);
    StringBuffer buf = new StringBuffer();
    List<String> result = new ArrayList<String>();
    while(matcher.find()){
        matcher.appendReplacement(buf, matcher.group());
        result.add(buf.toString());
        buf.setLength(0);
    }   

    matcher.appendTail(buf);
    result.add(buf.toString());
    String resultString = ""; 
    for(String s: result) { resultString += s + " "; }
    System.out.println("Final: \"" + resultString.trim() + "\"");
  }
}

Output:输出:

Final: "This Is A Test1234 A B C"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM