Java 如何在 IntelliJ IDEA 中自动拆分长字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24376980/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 11:51:19  来源:igfitidea点击:

How to split long strings in IntelliJ IDEA automatically?

javastringintellij-idea

提问by Cherry

I am writing a test with very long strings, and I need to split those strings:

我正在用很长的字符串编写测试,我需要拆分这些字符串:

private static final String TOO_LONG_JSON = "{field1:field1, field2:field2 ... fieldN:fieldN}";

so they would become:

所以他们会变成:

private static final String TOO_LONG_JSON = "{field1:field1, field2:field2" + 
    "{field3:field3, field4:field4,field6:field6, field7:field7}" +
    "{field8:field8, field9:field9,field10:field10, field11:field11}" +
    " ... fieldN:fieldN}";

Is it possible to set up IntelliJ IDEA to automatically split those long strings?

是否可以设置 IntelliJ IDEA 来自动拆分那些长字符串?

回答by mkierc

You can use auto-formatting (CTRL+ ALT+ L), after few changes in Code Style settings.

您可以使用自动格式化 ( CTRL+ ALT+ L),在代码样式设置中稍作更改后。

  • Press CTRL+ ALT+ Sto open Settings window
  • Find Code Style / Java section
  • Make sure to uncheck"Line Breaks" option and check"Ensure right margin is not exceeded" option
  • Press OK to accept changes you've made
  • CTRL+ ALT+S打开设置窗口
  • 查找代码样式/Java 部分
  • 确保取消选中“换行符”选项并选中“确保不超过右边距”选项
  • 按确定接受您所做的更改

Now when using auto-formatting (CTRL+ ALT+ L) long strings exceeding line character limit will be automatically cut into multiple lines.

现在,当使用自动格式化(CTRL+ ALT+ L)的长字符串超过行字符的限制会自动切断成多行。

回答by Gili Garibi

Same version - Community Edition. Here's the relevant section

相同版本 - 社区版。 这是相关部分

回答by DBDAN

I had to paste a long SQL String for a native query in my application. I think the real solution is to put your cursor inside the "" marks of this line of code typed manually: " " +

我不得不在我的应用程序中为本地查询粘贴一个很长的 SQL 字符串。我认为真正的解决方案是将光标放在手动键入的这行代码的 "" 标记内:" " +

When you paste the LONG STRING of text inside the quotation marks, IntelliJ will format each line of code also with \t and \n inside, for you.

当您将 LONG STRING 文本粘贴到引号内时,IntelliJ 还会为您格式化每一行代码,其中包含 \t 和 \n。