English 中文(简体)
改变内容后建造新护 of的更好方式
原标题:A better way of building a new string after swapping its contents

I am manipulating ssn. Input ="123456789" Output="896745123"

您从投入中抽取头3位数(即123位数),然后用最后2位数“89”交换,然后将“45”换成“67”。 以下是我使用CharArray的代码。 但我不喜欢。 这种方法(而不是测试)可以随时由许多用户使用。 我正在寻求更好的业绩、可读性和贸易安全解决办法。

我赞赏你的帮助。

@Test
    public void testSSNString(){

        String original="123456789";
        String result="896745123";
        char[] charResult=original.toCharArray();

        char temp=charResult[6];
        charResult[6]=charResult[0];
        charResult[0]=charResult[7];
        charResult[7]=charResult[1];
        charResult[1]=charResult[8];
        charResult[8]=charResult[2];
        charResult[2]=charResult[5];
        charResult[5]=charResult[4];
        charResult[4]=charResult[3];
        charResult[3]=temp;

        assertEquals(original.toCharArray(),charResult);

    }
最佳回答

你所给予的方式基本上是你在 Java业绩方面所能做的最佳方式。 使用阵列的速度比使用<代码>StringBuilder要快。

为了提高可读性,我仅作一些小改动,如为每轮产出提供新的阵列:

@Test
public void testSSNString() {
  String original = "123456789";
  String expected = "896745123";

  char[] in = original.toCharArray();
  char[] out = new char[9];
  out[0] = in[7];
  out[1] = in[8];
  out[2] = in[5];
  out[3] = in[6];
  out[4] = in[3];
  out[5] = in[4];
  out[6] = in[0];
  out[7] = in[1];
  out[8] = in[2];

  assertEquals(expected.toCharArray(), out);
}
问题回答

暂无回答




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签