如何使用Java中的字符串逐行反转大写和单独的单词?

时间:2017-10-24 20:33:12

标签: java

输入为:i love cake

输出必须是:Cake Love I

但实际结果是:I Love Cake

我得到了什么:

import java.util.regex.Pattern; 
public class yellow {

    static String reverseWords(String str){
        Pattern pattern = Pattern.compile("\\s");
        String[] temp = pattern.split(str);
        String result = "";

        for (int i = 0; i < temp.length; i++) {
            if (i == temp.length - 1)
                result = temp[i] + result;
            else
                result = " " + temp[i] + result;
        }
        return result;
    }

    public static void main(String[] args){
        String source = "i love cake";
        StringBuffer res = new StringBuffer();

        String[] strArr = source.split(" ");
        for (String str : strArr) {
            char[] stringArray = str.trim().toCharArray();
            stringArray[0] = Character.toUpperCase(stringArray[0]);
            str = new String(stringArray);

            res.append(str).append(" ");
        }
        System.out.print(res.toString());
    }
}

我做错了什么?

5 个答案:

答案 0 :(得分:0)

for (String str : strArr) {

}

这循环向前。你想要的是向后循环,或向后放置元素到字符串。我建议你向后循环并随时打印:

for (int i = strArr.length - 1; i >= 0; i--) {
    char[] stringArray = strArr[i].trim().toCharArray();
    stringArray[0] = Character.toUpperCase(stringArray[0]);
    System.out.println(new String(stringArray));
}

或者,你可以使用你从未在任何地方使用过的方便的reverseWords方法......虽然向后循环更快。可能。

答案 1 :(得分:0)

[EDITED] 使用字符串s为每一行调用此函数,然后打印换行符(如果您有多个句子并且期望它们在各自的行中)。

from __future__ import absolute_import

import logging
import argparse
import apache_beam as beam
import apache_beam.transforms.window as window

'''Normalize pubsub string to json object'''
# Lines look like this:
  # {'datetime': '2017-07-13T21:15:02Z', 'mac': 'FC:FC:48:AE:F6:94', 'status': 1}
def parse_pubsub(line):
    import json
    record = json.loads(line)
    return (record['mac']), (record['status']), (record['datetime'])

def run(argv=None):
  """Build and run the pipeline."""

  parser = argparse.ArgumentParser()
  parser.add_argument(
      '--input_topic', required=True,
      help='Input PubSub topic of the form "/topics/<PROJECT>/<TOPIC>".')
  parser.add_argument(
      '--output_table', required=True,
      help=
      ('Output BigQuery table for results specified as: PROJECT:DATASET.TABLE '
       'or DATASET.TABLE.'))
  known_args, pipeline_args = parser.parse_known_args(argv)

  with beam.Pipeline(argv=pipeline_args) as p:
    # Read the pubsub topic into a PCollection.
    lines = ( p | beam.io.ReadStringsFromPubSub(known_args.input_topic)
                | beam.Map(parse_pubsub)
                | beam.Map(lambda (mac_bq, status_bq, datetime_bq): {'mac': mac_bq, 'status': status_bq, 'datetime': datetime_bq})
                | beam.io.WriteToBigQuery(
                    known_args.output_table,
                    schema=' mac:STRING, status:INTEGER, datetime:TIMESTAMP',
                    create_disposition=beam.io.BigQueryDisposition.CREATE_IF_NEEDED,
                    write_disposition=beam.io.BigQueryDisposition.WRITE_APPEND)
            )

if __name__ == '__main__':
  logging.getLogger().setLevel(logging.INFO)
  run()

答案 2 :(得分:0)

这就是我所做的。

public class Main {

public static void main(String[] args) {
    reverse("I Love Cake");
}

public static void reverse( String string){
    String[] word =string.split(" "); // split by spaces
    int i = word.length-1;
    while (i>=0){
       // System.out.print(word[i].toUpperCase()+" ");//if you want in upper case
        System.out.print(word[i]+" ");
        i--;
      }
   }
}

答案 3 :(得分:0)

首先,你必须扭转字符串。

String[] words = source.split("\\s");
String reversedString = "";
for(int i = words.length -1; i>=0; i--){
    reversedString += words[i] + " ";
}

然后,您知道'a'字符的ASCII码是97,'A'是65.要从小写转换为大写,您将减去32。所有大写都在65到92之间。所有小的字母在97到124之间。 您希望仅在单词的开头加上字母(以空格或首字母开头)。

String capitalCase = "";
        for (int i = 0; i < reversedString.length(); i++) {
            char c = reversedString.charAt(i);
            if (c >= 97 && c <= 124) {
                if (i == 0) c -= 32;
                else if ((reversedString.charAt(i - 1) + "").equals(" ")) c -= 32;
            }
            capitalCase += c;
        }

现在你去System.out.println(capitalCase);

总的来说,您将拥有以下代码:

import java.util.Scanner;

public class yellow {
    public static void main(String[] args) {

        Scanner s = new Scanner(System.in);
        System.out.println("Enter a string:");
        String source = s.nextLine();

        String[] words = source.split("\\s");
        String reversedString = "";
        for (int i = words.length - 1; i >= 0; i--) {
            reversedString += words[i] + " ";
        }

        String capitalCase = "";
        for (int i = 0; i < reversedString.length(); i++) {
            char c = reversedString.charAt(i);
            if (c >= 97 && c <= 124) {
                if (i == 0) c -= 32;
                else if ((reversedString.charAt(i - 1) + "").equals(" ")) c -= 32;
            }
            capitalCase += c;
        }

        System.out.println(capitalCase);
    }
}

<强>输出:

Enter a string:
i love cake
Cake Love I 

答案 4 :(得分:0)

Java 8 * Apache Commons Lang

public static String reverseWordsInString(String str) {
    List<String> words = Pattern.compile("\\s+").splitAsStream(str)
                                .map(StringUtils::capitalize)
                                .collect(LinkedList::new, LinkedList::addFirst, (a, b) -> a.addAll(0, b));
    return words.stream().collect(Collectors.joining(StringUtils.SPACE));
}

Java 8

public static String reverseWordsInString(String str) {
    List<String> words = Pattern.compile("\\s+").splitAsStream(str)
                                .map(word -> Character.toUpperCase(word.charAt(0)) + word.substring(1).toLowerCase())
                                .collect(LinkedList::new, LinkedList::addFirst, (a, b) -> a.addAll(0, b));
    return words.stream().collect(Collectors.joining(" "));
}