구두점을 문자열 끝에서 시작 부분으로 이동하려면 어떻게 해야 합니까? (How can I move the punctuation from the end of a string to the beginning?)


문제 설명

구두점을 문자열 끝에서 시작 부분으로 이동하려면 어떻게 해야 합니까? (How can I move the punctuation from the end of a string to the beginning?)

문자열의 순서, 심지어 구두점까지 뒤집는 프로그램을 작성하려고 합니다. 하지만 내 뒤로 문자열이 인쇄될 때. 마지막 단어 끝에 있는 구두점은 개별 문자로 처리되지 않고 단어 끝에 유지됩니다.

마지막 단어에서 끝 구두점을 분리하여 이동할 수 있도록 하는 방법 주위에?

예: Hello my name is jason!

내가 원하는 것: !jason은 name my Hello

대신 jason! 내 이름은 안녕

import java.util.*;

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

        Scanner userInput = new Scanner(System.in);

        System.out.print("Enter a sentence: ");

        String input = userInput.nextLine();

        String[] sentence= input.split(" ");

        String backwards = "";

        for (int i = sentence.length ‑ 1; i >= 0; i‑‑) {
            backwards += sentence[i] + " ";
        }

        System.out.print(input + "\n");
        System.out.print(backwards);
        }
}

참조 솔루션

방법 1:

Manually rearranging Strings tends to become complicated in no time. It's usually better (if possible) to code what you want to do, not how you want to do it.

String input = "Hello my name is jason! Nice to meet you. What's your name?";

// this is *what* you want to do, part 1:
// split the input at each ' ', '.', '?' and '!', keep delimiter tokens
StringTokenizer st = new StringTokenizer(input, " .?!", true);
StringBuilder sb = new StringBuilder();
while(st.hasMoreTokens()) {
    String token = st.nextToken();
    // *what* you want to do, part 2:
    // add each token to the start of the string
    sb.insert(0, token);
}

String backwards = sb.toString();

System.out.print(input + "\n");
System.out.print(backwards);

Output:

Hello my name is jason! Nice to meet you. What's your name?
?name your What's .you meet to Nice !jason is name my Hello

This will be a lot easier to understand for the next person working on that piece of code, or your future self.

This assumes that you want to move every punctuation char. If you only want the one at the end of the input string, you'd have to cut it off the input, do the reordering, and finally place it at the start of the string:

String punctuation = "";
String input = "Hello my name is jason! Nice to meet you. What's your name?";
System.out.print(input + "\n");
if(input.substring(input.length() ‑1).matches("[.!?]")) {
    punctuation = input.substring(input.length() ‑1);
    input = input.substring(0, input.length() ‑1);
}

StringTokenizer st = new StringTokenizer(input, " ", true);
StringBuilder sb = new StringBuilder();
while(st.hasMoreTokens()) {
    sb.insert(0, st.nextToken());
}
sb.insert(0, punctuation);
System.out.print(sb);

Output:

Hello my name is jason! Nice to meet you. What's your name?
?name your What's you. meet to Nice jason! is name my Hello

방법 2:

You need to follow the below steps:

(1) Check for the ! character in the input

(2) If input contains ! then prefix it to the empty output string variable

(3) If input does not contain ! then create empty output string variable

(4) Split the input string and iterate in reverse order (you are already doing this)

You can refer the below code:

public static void main(String[] args) {
     Scanner userInput = new Scanner(System.in);
     System.out.print("Enter a sentence: ");
     String originalInput = userInput.nextLine();
     String backwards = "";
     String input = originalInput;

      //Define your punctuation chars into an array
       char[] punctuationChars = {'!', '?' , '.'};
        String backwards = "";

          //Remove ! from the input
         for(int i=0;i<punctuationChars.length;i++) {
          if(input.charAt(input.length()‑1) == punctuationChars[i]) {
              input = input.substring(0, input.length()‑1);
              backwards = punctuationChars[i]+"";
              break;
          }
        }

        String[] sentence= input.split(" ");


        for (int i = sentence.length ‑ 1; i >= 0; i‑‑) {
            backwards += sentence[i] + " ";
        }

        System.out.print(originalInput + "\n");

        System.out.print(input + "\n");
        System.out.print(backwards);
    }

방법 3:

Like the other answers, need to separate out the punctuation first, and then reorder the words and finally place the punctuation at the beginning.

You could take advantage of String.join() and Collections.reverse(), String.endsWith() for a simpler answer...

String input = "Hello my name is jason!";
String punctuation = "";
if (input.endsWith("?") || input.endsWith("!")) {
    punctuation = input.substring(input.length() ‑ 1, input.length());
    input = input.substring(0, input.length() ‑ 1);
}
List<String> words = Arrays.asList(input.split(" "));
Collections.reverse(words);
String reordered = punctuation + String.join(" ", words);
System.out.println(reordered);

방법 4:

The below code should work for you

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceSample {
    public static void main(String[] args) {
        String originalString = "TestStr?";
        String updatedString = "";
        String regex = "end\\p{Punct}+|\\p{Punct}+$";
        Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(originalString);
    while (matcher.find()) {
            int start = matcher.start();
            updatedString = matcher.group() + originalString.substring(0, start);<br>
        }
        System.out.println("Original ‑‑>" + originalString + "\nReplaced ‑‑>" +      updatedString);
    }
}

방법 5:

Don't split by spaces; split by word boundaries. Then you don't need to care about punctuation or even putting spaces back, because you just reverse them too!

And it's only 1 line:

Arrays.stream(input.split("\\b"))
    .reduce((a, b) ‑> b + a)
    .ifPresent(System.out::println);

See live demo.

(by Jason_SilvaduckstepdeveloperAdamRamachandra ReddyBohemian)

참조 문서

  1. How can I move the punctuation from the end of a string to the beginning? (CC BY‑SA 2.5/3.0/4.0)

#split #string #arrays #loops #java






관련 질문

오류: 이 범위에서 '분할'이 선언되지 않았습니다. (error: ‘split’ was not declared in this scope)

화살표 문자가 포함된 문자열 분할 (Split a string containing arrow characters)

문자 수로 문자열의 특정 부분 가져오기 (Take specific part of a string by character count)

VBScript: 새로운 분할 항목이 있는 리조트 문자열 및 그룹 (VBScript: Resort String and group with new Split Item)

python 태그에서 단어와 숫자 나누기 (Split words and numbers from tags python)

구두점을 문자열 끝에서 시작 부분으로 이동하려면 어떻게 해야 합니까? (How can I move the punctuation from the end of a string to the beginning?)

쉼표로 문자열을 분할하지만 대괄호 또는 따옴표로 묶인 쉼표는 무시하십시오. (Split string by comma but ignore commas in brackets or in quotes)

숫자를 나누고 점 뒤에 하나의 숫자를 유지하십시오. (Split the number and keep one number after the dot)

Oracle에서 쉼표로 구분된 문자열의 최대 개수를 얻는 방법은 무엇입니까? (How to get maximum COUNT of comma separated string in Oracle?)

분할 방법을 사용하여 텍스트 파일에서 범주를 열로 분리 (Using the split method to separate categories into columns from a text file)

Powershell에서 문자열 분할 및 추가 (Splitting and Adding String in Powershell)

원래 문자열 포인터를 수정하지 않는 strtok_r() 및 strsep()에 대한 C-문자열 대안? (C-string alternatives to strtok_r() and strsep() that don't modify the original string pointer?)







코멘트