Home > Blockchain >  I want to go to a new line every time a \n appears in a given string
I want to go to a new line every time a \n appears in a given string

Time:09-30

Im making a programm that takes a string as a parameter and if it reads in a \n value it will skip too a new line however for some reason java doesnt recognise '\n' i want to replace all occurences of \n with ! so that i can use a char array to do the new line thing but the replace all doesnt work when i plug in \n any ideas how i can fix my issue

  public void newLine(String gg) {
     int temp = 0;
      String x = gg.replaceAll("\n", "!");
      for(char pp: x.toCharArray()) {
          if(pp == '!') {
              System.out.println();
          }
          System.out.printf("%s",pp);
      }
  }

'''

CodePudding user response:

\n is a newline character, but you want to replace the character sequence of a literal backslash then an n, which in java is coded as "\\n" (you must escape the escape character).

Escape the backslash and use replace():

gg = gg.replace("\\n", "!");

Note that replace() replaces all occurrences, but replaceAll() uses regex to match whereas replace() matches literally.

CodePudding user response:

Recall that in Java, strings are immutable. Additionally, using a for each loop uses a copy of every element in an iterable object. I am not quite sure what you are trying to do, but this method replaces every newline escape seqeuence with an exclamation mark and prints the result.

public void newLine (String gg) {
    String[] ggArray = gg.split(" ");
    for (int i = 0; i < ggArray.length; i  ) {
        ggArray[i] = ggArray[i].replace("\n", "!");
    }
    gg = String.join(" ", ggArray);
    System.out.println(gg);
}
  • Related