如何利用Java中的每个字符串?

时间:2016-01-26 11:19:54

标签: java

我正在研究这个java方法,试图将字符串中的第n个单词大写,并且无法返回retVal变量的值

class MyTesting
{
public static void main (String[] args) throws java.lang.Exception
{
    capitalizeEveryNthWord("this is a String", 3, 3);
}

// Take a single-spaced <sentence>, and capitalize every <n> word starting   with <offset>.

public static String capitalizeEveryNthWord(String sentence, Integer offset,     Integer n) {
String[] parts = sentence.split(" ");
String retVal = "";
for (int idx = 0; idx < offset; idx++)
{
    retVal.concat(parts[idx] + " ");
}
for (int idx = offset; idx < parts.length; idx++)
{
    if (idx - offset % n == 0)
    {
        retVal.concat(parts[idx] + "-");
    }
    else
    {
        retVal.concat(parts[idx] + " ");
    }
}
System.out.println(retVal);
return retVal;
}
}

3 个答案:

答案 0 :(得分:3)

concat()返回一个值,它不会修改您调用该方法的字符串。您需要将其用作retVal = retVal.concat(...)或仅retVal += ...

答案 1 :(得分:2)

Java的String类是不可变的。 String.concat()会将连接作为新的String对象返回。

您可以使用retVal = retVal.concat(...),也可以使用StringBuilder

以下作品:

class MyTesting
{
  public static void main (String[] args) throws java.lang.Exception
  {
    capitalizeEveryNthWord("this is a sentence that is being tested", 3, 3);
  }

  // Take a single-spaced <sentence>, and capitalize every <n> word starting   with <offset>.
  public static String capitalizeEveryNthWord(String sentence, Integer offset, Integer n) {
    String[] parts = sentence.split(" ");
    String retVal = "";
    for (int idx = 0; idx < offset; idx++)
    {
        retVal += parts[idx] + " ";
    }
    for (int idx = offset; idx < parts.length; idx++)
    {
        if ((idx - offset) % n == 0) // added parantheses
        {
            retVal += Character.toUpperCase(parts[idx].charAt(0)) + parts[idx].substring(1) + " "; // make the first character uppercase.
        }
        else
        {
            retVal += parts[idx] + " ";
        }
    }
    System.out.println(retVal);
    return retVal;
  }
}

更有效的方法是:

public static String capitalizeEveryNthWord(String sentence, Integer offset, Integer n) {
  StringBuilder sb = new StringBuilder(sentence);
  int wordIdx = 0;
  boolean newWord = true;
  for (int i = 0; i < sb.length(); i++) {
    char c = sb.charAt(i);
    if (c == ' ') {
      wordIdx++; // assumes single space between words.
      newWord = true;
    } else if (newWord) {
      if (wordIdx >= offset && (wordIdx - offset) % n == 0) {
        sb.setCharAt(i, Character.toUpperCase(c));
      }
      newWord = false;
    }
  }
  return sb.toString();
}

第二种方法只分配一个缓冲区,然后就地修改以大写单词。以前的方法会在每次调用String时分配新的+=个对象(这有时会被编译器优化掉,但据我所知,它不能保证。)

答案 2 :(得分:0)

使用toUpperCase()方法并使用返回值

String retVal = retVal.concat(...).toUpperCase();