根据字符串模式数组对字符串进行排序

huangapple go评论77阅读模式
英文:

Sort String based on a pattern array of String

问题

我需要按照它们在模式数组中的顺序对一个包含单词的字符串进行排序:

String[] pattern = {"Burger", "Fries", "Chicken", "Pizza", "Sandwich", "Onionrings", "Milkshake", "Coke"};

String s = "Chicken Coke Chicken Chicken Onionrings Coke Burger Milkshake Milkshake Burger Coke Milkshake Burger Onionrings Onionrings Coke Chicken Burger Fries Milkshake"; // 输入字符串

期望输出

"Burger Burger Burger Burger Fries Chicken Chicken Chicken Chicken Onionrings Onionrings Onionrings Milkshake Milkshake Milkshake Milkshake Coke Coke Coke Coke" // 输出字符串
英文:

I need to sort a string of words in an order those words are placed in the pattern array:

String[] pattern = {"Burger", "Fries", "Chicken", "Pizza", "Sandwich", "Onionrings", "Milkshake", "Coke"};

String s = "Chicken Coke Chicken Chicken Onionrings Coke Burger Milkshake Milkshake Burger Coke Milkshake Burger Onionrings Onionrings Coke Chicken Burger Fries Milkshake"; // input string

Expect

"Burger Burger Burger Burger Fries Chicken Chicken Chicken Chicken Onionrings Onionrings Onionrings Milkshake Milkshake Milkshake Milkshake Coke Coke Coke Coke" // output string

答案1

得分: 5

你可以使用 List 来使单词具有索引,然后使用这些索引对单词进行排序。

  • 获取一个单词的List以便能够对它们进行索引。
  • 将你的String拆分为一个数组,以便能够对单词进行排序。
  • 根据它们在List中的索引对它们进行sort排序。
  • 使用join将单词连接成一个String
// INPUTS
String s = "Chicken Coke Chicken Chicken Onionrings Coke Burger Milkshake Milkshake Burger Coke Milkshake Burger Onionrings Onionrings Coke Chicken Burger Fries Milkshake";
String expect = "Burger Burger Burger Burger Fries Chicken Chicken Chicken Chicken Onionrings Onionrings Onionrings Milkshake Milkshake Milkshake Milkshake Coke Coke Coke Coke";
String[] pattern = {"Burger", "Fries", "Chicken", "Pizza", "Sandwich", "Onionrings",
    "Milkshake", "Coke"};

// 获取模式的List以使用indexOf方法
List<String> listPatterns = Arrays.asList(pattern);

// 拆分为单词
String[] values = s.split(" ");

// 根据List中的索引进行排序
Arrays.sort(values, Comparator.comparing(listPatterns::indexOf));

// 使用join重建字符串
String result = String.join(" ", values);

// 输出 true
System.out.println(result.equals(expect));

<!-- -->

英文:

You may use a List to be able to get index from word, then sort the words using these indexes

  • Get a List os the words to get them indexable
  • split your String into an array to be able to sort the words
  • sort them based on their indices in the List
  • join the words to get one String

<!-- -->

// INPUTS
String s = &quot;Chicken Coke Chicken Chicken Onionrings Coke Burger Milkshake Milkshake Burger Coke Milkshake Burger Onionrings Onionrings Coke Chicken Burger Fries Milkshake&quot;;
String expect = &quot;Burger Burger Burger Burger Fries Chicken Chicken Chicken Chicken Onionrings Onionrings Onionrings Milkshake Milkshake Milkshake Milkshake Coke Coke Coke Coke&quot;;
String[] pattern = {&quot;Burger&quot;, &quot;Fries&quot;, &quot;Chicken&quot;, &quot;Pizza&quot;, &quot;Sandwich&quot;, &quot;Onionrings&quot;,
    &quot;Milkshake&quot;, &quot;Coke&quot;};

// Get the patterns a list to get the indexOf method
List&lt;String&gt; listPatterns = Arrays.asList(pattern);

// Split in words
String[] values = s.split(&quot; &quot;);

//Sort base on index in list
Arrays.sort(values, Comparator.comparing(listPatterns::indexOf));

// Rebuild a string by joining
String result = String.join(&quot; &quot;, values);

// true
System.out.println(result.equals(expect));

答案2

得分: 1

因为问题中没有包含任何代码,所以我只会发布一个解决方案的大致草图。

我会通过将String拆分为单词列表,然后使用Comparator来对这些单词进行排序,并用空格将它们重新连接起来。

编写Comparator的常见方法是为相互比较的两个对象分配一个int值,从一个对象中减去另一个对象,然后将其作为比较结果返回。

Comparator中,我会使用两个单词在pattern数组中的索引作为比较的基础。

英文:

Since the question does not contain any code, I will only post a rough sketch of a solution.

I would approach the problem by splitting the String in a list of words, then use a Comparator to sort those words and re-join them with separating blanks.

A common way to write Comparators is to assign the both objects compared against each other an int-value, subtract one from the other and return that as the comparison result.

In the Comparator, I would use the index of the two words compared against each other in the pattern-array as base for comparison.

答案3

得分: 0

尝试这个

    String[] pattern = {"汉堡", "薯条", "鸡肉", "比萨", "三明治", "洋葱圈", "奶昔", "可乐"};

    // 创建模式到索引的映射。{汉堡=0, 薯条=1, 鸡肉=2, ...}
    Map<String, Integer> patternMap = IntStream.range(0, pattern.length).boxed()
        .collect(Collectors.toMap(i -> pattern[i], Function.identity()));

    // 使用 patternMap 对单词进行排序
    String s = "鸡肉 可乐 鸡肉 鸡肉 洋葱圈 可乐 汉堡 奶昔 奶昔 汉堡 可乐 奶昔 汉堡 洋葱圈 洋葱圈 可乐 鸡肉 汉堡 薯条 奶昔"; // 输入字符串
    String[] result = Arrays.stream(s.split("\\s+"))
        .sorted(Comparator.comparing(word -> patternMap.get(word)))
        .toArray(String[]::new);

    System.out.println(Arrays.toString(result));

输出

    [汉堡, 汉堡, 汉堡, 汉堡, 薯条, 鸡肉, 鸡肉, 鸡肉, 鸡肉, 洋葱圈, 洋葱圈, 洋葱圈, 奶昔, 奶昔, 奶昔, 奶昔, 可乐, 可乐, 可乐, 可乐]
英文:

Try this.

String[] pattern = {&quot;Burger&quot;, &quot;Fries&quot;, &quot;Chicken&quot;, &quot;Pizza&quot;, &quot;Sandwich&quot;, &quot;Onionrings&quot;, &quot;Milkshake&quot;, &quot;Coke&quot;};

// make pattern to index map. {Burger=0, Fries=1, Chicken=2, ...}
Map&lt;String, Integer&gt; patternMap = IntStream.range(0, pattern.length).boxed()
    .collect(Collectors.toMap(i -&gt; pattern[i], Function.identity()));

// sort words using patternMap
String s = &quot;Chicken Coke Chicken Chicken Onionrings Coke Burger Milkshake Milkshake Burger Coke Milkshake Burger Onionrings Onionrings Coke Chicken Burger Fries Milkshake&quot;; // input string
String[] result = Arrays.stream(s.split(&quot;\\s+&quot;))
    .sorted(Comparator.comparing(word -&gt; patternMap.get(word)))
    .toArray(String[]::new);

System.out.println(Arrays.toString(result));

output:

[Burger, Burger, Burger, Burger, Fries, Chicken, Chicken, Chicken, Chicken, Onionrings, Onionrings, Onionrings, Milkshake, Milkshake, Milkshake, Milkshake, Coke, Coke, Coke, Coke]

答案4

得分: -1

这是一个按字母顺序排序的代码示例:

public class MainProgram {

    public static void main(String[] args) {
        String temp;
        String[] pattern = {"Burger", "Fries", "Chicken", "Pizza", "Sandwich", "Onionrings", "Milkshake", "Coke"};
          //对字符串进行排序
        for (int i = 0; i < pattern.length; i++) 
        {
            for (int j = i + 1; j < pattern.length; j++) { 
                if (pattern[i].compareTo(pattern[j])>0) 
                {
                    temp = pattern[i];
                    pattern[i] = pattern[j];
                    pattern[j] = temp;
                }
            }
        }
      //在按字母顺序排序后显示字符串
        System.out.print("按字母顺序排序的字符串:");
        for (int i = 0; i <= pattern.length - 1; i++) 
        {
            System.out.print(pattern[i] + ", ");
        }
        
    }

}
英文:

here is code to sort alphabetically

public class MainProgram {

	public static void main(String[] args) {
		String temp;
		String[] pattern = {&quot;Burger&quot;, &quot;Fries&quot;, &quot;Chicken&quot;, &quot;Pizza&quot;, &quot;Sandwich&quot;, &quot;Onionrings&quot;, &quot;Milkshake&quot;, &quot;Coke&quot;};
		  //Sorting the strings
        for (int i = 0; i &lt; pattern.length; i++) 
        {
            for (int j = i + 1; j &lt; pattern.length; j++) { 
                if (pattern[i].compareTo(pattern[j])&gt;0) 
                {
                    temp = pattern[i];
                    pattern[i] = pattern[j];
                    pattern[j] = temp;
                }
            }
        }
      //Displaying the strings after sorting them based on alphabetical order
        System.out.print(&quot;Strings in Sorted Order:&quot;);
        for (int i = 0; i &lt;= pattern.length - 1; i++) 
        {
            System.out.print(pattern[i] + &quot;, &quot;);
        }
        
	}

}

huangapple
  • 本文由 发表于 2020年8月30日 15:38:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/63655094.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定