2016-09-20 13 views
-5

入力文字列は です。文字列= "comp!ex、ex.amp!e";区切り文字を含む文字列をJavaでも逆転

出力は である必要があります。文字列出力= "pmoc!xe、xe.pma!e";入力上

static void reverseEachWordOfString(String inputString) 
{ 
      String[] words = inputString.split("[\\s,!.]"); 

      String reverseString = ""; 

      for (int i = 0; i < words.length; i++) 
      { 
       String word = words[i]; 

       String reverseWord = ""; 

       for (int j = word.length()-1; j >= 0; j--) 
       { 
        reverseWord = reverseWord + word.charAt(j); 
       } 

       reverseString = reverseString + reverseWord + " "; 
      } 
} 
+2

出力は何ですか?デバッガを使って問題が何かを調べようとしましたか? – Jens

+0

あなたのアプローチの問題の一部は、区切り文字を破棄することです。 'String.split'を使わない方が簡単です。 –

+0

正しい正規表現が見つかると、 'String.split()'を使ってワード境界で(つまり、すべての単語の前後に)分割することができると思います。それが本当であれば、言葉を逆転させ、言葉ではない部分文字列を逆転させないでください。 –

答えて

0

次の例の反復:

はこの試み。現在の文字が正規表現に一致するまで停止します。表現はコードで説明されています。それは、入力を分割すべきより多くの特殊文字によって拡張される可能性があります。

  • 特殊文字の入力開始とインデックス
  • または最後のストップし、現在の特殊文字
  • または最後の入力

の停止と終了が逆転してしまいますとに添付される間subtring出力文字列。あなたの質問を編集し、必要な情報を提供しない場合は、より多くの情報を提供してください。

public static void main(String[] args) 
{ 
    String reversed = reverse("comp!ex, ex.amp!e"); 

    // 
    // Just to test... 
    // 
    String expectedOutput = "pmoc!xe, xe.pma!e"; 

    if(expectedOutput.equals(reversed) == false) 
    { 
     throw new IllegalStateException(reversed); 
    } 
} 

public static String reverse(String input) 
{ 
    // 
    // Regular expression to match characters that should split the string. 
    // ! or . or , or 'a sequence of whitespace' 
    // 
    String specialCharExpression = "!|\\.|,| *"; 

    StringBuilder result = new StringBuilder(); 

    int fragmentStart = 0; 

    for(int i = 0; i < input.length(); i++) 
    { 
     String currentChar = input.charAt(i) + ""; 

     if(currentChar.matches(specialCharExpression) 
      || i == input.length() - 1) 
     { 
      result 
       .append(new StringBuilder(input.substring(fragmentStart, i)) 
        .reverse().toString()); 
      result.append(currentChar); 

      fragmentStart = i + 1; 
     } 
    } 

    return result.toString(); 
} 

0

あなたが始めることができ、そこからスニペットの下に検索。コードには、何が行われたかを説明する追加のコメントがあります。

String sentence = "comp!ex, ex.amp!e"; 
String[] split = sentence.split("[\\s,!.]"); 
StringBuilder out = new StringBuilder(sentence.length()); 
StringBuilder tmp = new StringBuilder(sentence.length()); 
for (String s : split) { 
    // reset the length and reuse the tmp StringBuilder 
    tmp.setLength(0); 
    // append the part the the temporary StringBuilder 
    tmp.append(s); 
    // append the reversed part to the output StringBuilder 
    out.append(tmp.reverse()); 
    // if the length of the input is longer then the output 
    // we need to add the separator char from the input 
    if (sentence.length() > out.length()) { 
     out.append(sentence.charAt(out.length())); 
    } 
} 
System.out.println("input : " + sentence); 
System.out.println("reversed: " + out); 

出力

input : comp!ex, ex.amp!e 
reversed: pmoc!xe, xe.pma!e 
0

これは、文字列を分割せずに特殊文字を含む文字列を逆にする別の方法です。

  • Stringからcharに変換します。
  • char[]char[]のパラメータとループを使用する方法を記述します。
  • char[index]がアルファベットかどうかを確認する方法を書いてください。
  • char[index]がアルファベットでない場合は開始インデックスと終了インデックスを格納し、開始インデックスと 終了インデックスを使用してchar[]に要素を入れ替えます。ここで

作業codeです:

public static boolean isAlphabet(char x) { 
     return ((x >= 'A' && x <= 'Z') || (x >= 'a' && x <= 'z')); 
    } 

public static void reverse(char ch[]) { 
    int l = 0; 
    int startIndex = 0; 
    int endIndex = 0; 
    while (l < ch.length - 1) { 
     if (isAlphabet(ch[l])) { 
      l++; 
     } else { 
      endIndex = l - 1; 
      while (startIndex < endIndex){ 
       char temp = ch[startIndex]; 
       ch[startIndex] = ch[endIndex]; 
       ch[endIndex] = temp; 
       endIndex--; 
       startIndex++; 
      } 
      l++; 
      startIndex = l; 
      } 
     } 
    } 

    public static void main(String[] args) throws java.lang.Exception { 
     String inputString = "comp!ex, ex.amp!e"; 
     char[] ch = inputString.toCharArray(); 
     reverse(ch); 
     String reverseString = new String(ch); 
     System.out.println(reverseString); 
    } 

入力:comp!ex, ex.amp!e出力:pmoc!xe, xe.pma!e

whitespaceStringを分割することによって、あなたは同じisAlphabetreverse方法を使用することができます。

Code

String inputString = "comp!ex, ex.amp!e"; 
String[] splitArray = inputString.split("\\s"); 
char[] ch1 = splitArray[0].toCharArray(); 
reverse(ch1); 
char[] ch2 = splitArray[1].toCharArray(); 
reverse(ch2); 
StringBuilder reverseString = new StringBuilder(); 
reverseString.append(ch1); 
reverseString.append(" "); 
reverseString.append(ch2); 
System.out.println(reverseString.toString()); 

出力:

Input : comp!ex, ex.amp!e 
Output: pmoc!ex, xe.pma!e 
0

スタック

の使用はまた、あなたが区切り文字の任意の数を追加することができます方法isDelimiter()がありますソリューション。

static String reverseEachWordOfString(String inputString) { 

    StringBuffer reversedString = new StringBuffer(); 
    Stack<Character> stack = new Stack<Character>(); 

    for(int i=0;i<inputString.length();i++){ 
               // Get each character 
     char character = inputString.charAt(i); 
     if(isDelimiter(character)) {    // If character is delimiter 
      popInto(stack, reversedString);  // Then pop stack into output string 
      reversedString.append(character); // And append the delimiter 
     } else 
      stack.push(character);    // Else push character onto the stack 
    } 
    popInto(stack, reversedString);    // In the end pop stack into output string 

    return reversedString.toString(); 
} 

private static void popInto(Stack<Character> stack, StringBuffer str) { 
    while(!stack.empty()) { 
     str.append(stack.pop()); 
    } 
} 

private static boolean isDelimiter(char character) { 
    return character == ' ' || character == '.' || character == ',' || character == '!'; 
} 
関連する問題