【问题标题】:String to char array and to string array字符串到字符数组和字符串数组
【发布时间】:2013-04-15 07:31:08
【问题描述】:

如何将字符数组转换为字符串数组?

例如"Text not text" → "Text not text" as char array → "Text" "not" "text"

我知道如何"Text not text" → "Text not text",但不知道如何

"Text not text" as char array → "Text" "not" "text"

这是代码示例,但它不起作用

public class main {
    public static void main(String[] args) {
        StringBuffer inString = new StringBuffer("text not text");
        int n = inString.toString().replaceAll("[^a-zA-ZА-Я а-я]", "")
                .split(" ").length;
        char[] chList = inString.toString().toCharArray();
        System.out.print("Text splited by chars - ");
        for (int i = 0; i < chList.length; i++) {
            System.out.print(chList[i] + " ");
        }
        System.out.println();
        String[] temp = new String[n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < chList.length; j++) {
                if (chList[j] != ' ') {
                    temp[i] = new String(chList);
                }
            }
            System.out.println(temp[i]);
        }
    }

}

【问题讨论】:

  • 为什么要创建String[n]?你想要每个字符的字符串吗?或字符串作为空格数+1?
  • 当您必须检测单词时,这是可能的......!

标签: java arrays string char


【解决方案1】:

简短的甜蜜答案是from anvarik。但是,如果您需要展示一些工作(也许这是家庭作业?),以下代码将手动构建列表:

char[] chars = "text not text".toCharArray();

List<String> results = new ArrayList<String>();
StringBuilder builder = new StringBuilder();

for (int i = 0; i < chars.length; i++) {
  char c = chars[i];

  builder.append(c);

  if (c == ' ' || i == chars.length - 1) {
    results.add(builder.toString().trim());
    builder = new StringBuilder();
  }
}

for (String s : results) {
  System.out.println(s);
}

【讨论】:

  • 正确但在字典中搜索时可能,例如单词检测器!!
  • 但如果空格只打断单词?
【解决方案2】:

使用String.split() 方法。

【讨论】:

  • 如果问题是“如何将句子拆分为单词?”,这当然是一个简单的答案
  • 问题是如何将字符数组转换回单词!
  • 将char数组转换为String,并拆分字符串。
【解决方案3】:

我认为如果在将“Text not text”转换为 $ 符号时替换所有空格,那么结果字符串将变为 'T e x t$ n o t$ t e x t'

字符串 ex= ex.replaceAll("\s","$");

在将其转换回来时,您可以再次将 $ 替换为空格。

除此之外,我似乎想不出任何其他方法可以在拆分时保持单词的含义。

【讨论】:

  • 如果只有空格不能用空格?
【解决方案4】:

所以你有一个 char 数组,我说得对吗:

char[] chars = new char[] {'T', 'e', 'x', 't', ' ', 'n', 'o', 't', ' ', 't', 'e', 'x', 't'};

那么你想要得到的是单独的单词Textnottext??

如果是这样,请执行以下操作:

String newString = new String(chars);
String[] strArray = newString.split(" ");

现在strArray 是您的数组。

【讨论】:

  • 不正确。然后我的文本将由相同的拆分文本完成
  • @AntonArtemov 嗯……它正确的。也许你还没有解释你作业的所有规则?
猜你喜欢
  • 2014-10-24
  • 2022-08-14
  • 1970-01-01
  • 2016-06-11
  • 2015-04-16
  • 2014-04-18
  • 1970-01-01
  • 2011-12-09
  • 1970-01-01
相关资源
最近更新 更多