I'm looking for the way of replacing each char of a Java String for the character+ a blank (except the last one or removing the trailing blank at the end)
The idea is from STACKOVERFLOW return S T A C K O V E R F L O W. Is possible to do this with a regexp or should I iterate the string?
Thanks
"StackOverFlow".replaceAll(".(?!$)", "$0 "));
Go with
str.replaceAll("(?<!^)(?!$)", " ");
or equivalent
str.replaceAll("(?<=.)(?!$)", " ");
...or if you want to add space character just behind non-space character, then use
str.replaceAll("(?<=\S)(?!$)", " ");
...and if you want to prevent double spaces (in case some space is already there), then use
str.replaceAll("(?<=\S)(?!\s)(?!$)", " ");
There's no need for a regex.
Just iterate over the String and use a StringBuilder:
String withSpaces = addSpaces("StackOverflow");
public String addSpaces(String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
sb.append(s.charAt(i)).append(" ");
}
return sb.substring(0, sb.length() - 1);
}
Related
Thanks for checking out my question.
Here the user enter the string in the format: "xD xS xP xH". The program takes the string, splits it on the space bar, then uses regex to parse the string. There is an issue with my "final string regex" and I am not sure where.
final String regex = "([0-9]+)[D|d]| ([0-9]+)[S|s]| ([0-9]+)[P|p]| ([0-9]+)[H|h]";
Lastly, the loop prints out only the value for D so I suspect it reaches an error moving to match S or s.
public class parseStack
{
public parseStack()
{
System.out.print('\u000c');
String CurrencyFormat = "xD xS xP xH";
System.out.println("Please enter currency in the following format: \""+CurrencyFormat+"\" where x is any integer");
Scanner scan = new Scanner(System.in);
String currencyIn = scan.nextLine();
currencyFinal = currencyIn.toUpperCase();
System.out.println("This is the currency you entered: "+currencyFinal);
String[] tokens = currencyFinal.split(" ");
final String input = tokens[0];
final String regex = "([0-9]+)[D|d]| ([0-9]+)[S|s]| ([0-9]+)[P|p]| ([0-9]+)[H|h]";
if (input.matches(regex) == false) {
throw new IllegalArgumentException("Input is malformed.");
}
long[] values = Arrays.stream(input.replaceAll(regex, "$1 $2 $3 $4").split(" "))
.mapToLong(Long::parseLong)
.toArray();
for (int i=0; i<values.length; i++)
{
System.out.println("value of i: "+i+ " |" +values[i]+ "|");
}
//pause to print
System.out.println("Please press enter to continue . . . ");
Scanner itScan = new Scanner(System.in);
String nextIt = itScan.nextLine();
}
}
Your regular expression should be [\d]+[DdSsPpHh].
The problem you are having is you split the string into chunks, then you match chunks with a RegEx that matches the original string that you have split.
HOWEVER this answer only addresses a problem in your code. Your routine doesn't seem to cater your expectation. And your expectation is not clear at all.
EDIT
Added the multidigit requirement.
Your regex can be simplified somewhat.
"(?i)(\d+d) (\d+s) (\d+p) (\d+h)"
will do a case-insensitive match against multiple digits ( \d+ )
This can be further simplified into
"(?i)(\d+[dsph])"
which will iteratively match the various groups in your currency string.
First of all your regex looks a bit to complex. You input format is "xD xS xP xH" also you are converting the input to uppercase currencyIn = currencyIn.toUpperCase(); but this isn't the problem.
The problem is
String[] tokens = currencyIn.split(" ");
final String input = tokens[0];
You are splitting the input and only use the first part which would be "xD"
The fixed code would look like:
String currencyIn = scan.nextLine();
currencyIn = currencyIn.toUpperCase();
System.out.println("This is the currency you entered: "+currencyIn);
final String regex = "([0-9]+)D ([0-9]+)S ([0-9]+)P ([0-9]+)H";
if (!currencyIn.matches(regex)) {
throw new IllegalArgumentException("Input is malformed.");
}
long[] values = Arrays.stream(currencyIn.replaceAll(regex, "$1 $2 $3 $4").split(" "))
.mapToLong(Long::parseLong)
.toArray();
for (int i=0; i<values.length; i++) {
System.out.println("value of i: "+i+ " |" +values[i]+ "|");
}
I've searched about everywhere but I just can't find anything very concrete. I've been working on this code for awhile now but it keeps stumping me.
public static void main(String[] args) {
System.out.println(palindrome("word"));
}
public static boolean palindrome(String myPString) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a word:");
String word = in.nextLine();
String reverse = "";
int startIndex = 0;
int str = word.length() -1;
while(str >= 0) {
reverse = reverse + word.charAt(i);
}
}
There's a lot of ways to accomplish this using a while loop.
Thinking about simplicity, you can imagine how could you do this if you had a set of plastic separated character in a table in front of you.
Probably you'll think about get the second character and move it to the begin, then get the third and move to begin, and so on until reach the last one, right?
0123 1023 2103 3210
WORD -> OWRD -> ROWD -> DROW
So, you'll just need two code:
init a variable i with 1 (the first moved character)
while the value of i is smaller than total string size do
replace the string with
char at i plus
substring from 0 to i plus
substring from i+1 to end
increment i
print the string
The process should be:
o + w + rd
r + ow + d
d + row +
drow
Hope it helps
Here is an piece of code I write a while back that uses almost the same process. Hope it helps!
String original;
String reverse = "";
System.out.print("Enter a string: ");
original = input.nextLine();
for(int x = original.length(); x > 0; x--)
{
reverse += original.charAt(x - 1);
}
System.out.println("The reversed string is " +reverse);
I am attempting to write a program that reverses a string's order, even the punctuation. But when my backwards string prints. The punctuation mark at the end of the last word stays at the end of the word instead of being treated as an individual character.
How can I split the end punctuation mark from the last word so I can move it around?
For example:
When I type in : Hello my name is jason!
I want: !jason is name my Hello
instead I get: jason! is name my Hello
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);
}
}
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
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);
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);
}
}
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);
}
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.
I have a string xyz a z. How to split it into xyz az. That is splitting the string into two parts taking first white space as the split point. Thanks
Use String.split with the second limit parameter. Use a limit of 2.
The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times
Try this
String givenString = "xyz a z";
String[] split = givenString.split(" ");
StringBuffer secondPart = new StringBuffer();
for (int i = 1; i < split.length; i++) {
secondPart.append(split[i]);
}
StringBuffer finalPart = new StringBuffer();
finalPart.append(split[0]);
finalPart.append(" ");
finalPart.append(secondPart.toString());
System.out.println(finalPart.toString());
Do like this
public static void main(String []args){
String a= "xyz a z";
String[] str_array=a.split(" ");
System.out.print(str_array[0]+" ");
System.out.println(str_array[1]+str_array[2]);
}
Try this
String Str = new String("xyz a z");
for (String retval: Str.split(" ", 2)){
System.out.println(retval);
You need to use String.split with limit of 2 as it will be applied (n-1) times, in your case (2-1 = 1 ) time
So it will consider first space only.
But still you will get the result as xyz and a z, you will still have to get rid of that one more space between a z
Try this
String path="XYZ a z";
String arr[] = path.split(" ",2);
String Str = new String("xyz a z");
for(int i=0;i<arr.length;i++)
arr[i] = arr[i].replace(" ","").trim();
StringBuilder builder = new StringBuilder();
for(String s : arr) {
builder.append(s);
builder.append(" ");
}
System.out.println(builder.toString());
In the for loop you can append a space between two arrays using builder.append(" ").
This question already has answers here:
Removing whitespace from strings in Java
(37 answers)
Closed 6 years ago.
I have a programming assignment and part of it requires me to make code that reads a line from the user and removes all the white space within that line.
the line can consist of one word or more.
What I was trying to do with this program is have it analyze each character until it finds a space and then save that substring as the first token. then loop again until it reaches no more tokens or the end of the line.
I keep on getting this when I try to compile it:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
at java.lang.String.charAt(String.java:694)
at trim.main(trim.java:23)
Here is the code
import java.util.Scanner ;
import java.lang.Character;
import java.lang.String ;
public class trim
{
public static void main (String[]args)
{
String a ;
String b ;
String c ;
char aChar ;
int i = 0 ;
Scanner scan = new Scanner(System.in);
a = scan.nextLine();
a =a.trim() ;
for ( ; i >= 0 ; i++ )
{
aChar = a.charAt(i) ;
if (aChar != 32)
{
a = a.substring(0,i+1);
}
else
{
b = a.substring(i,160) ;
b= b.trim();
c = c + a ;
c = c.trim() ;
a = b ;
i = 0 ;
}
if (b.equals(null))
{
i = -1 ;
}
}
}
}
easier ways to do this is appreciated, but I still want to get this program working.
and I can't use sentinels in the input.
Thanks everybody for all the help,
I will use the simpler method , and will read the javadoc.
java.lang.String class has method substring not substr , thats the error in your program.
Moreover you can do this in one single line if you are ok in using regular expression.
a.replaceAll("\\s+","");
Why not use a regex for this?
a = a.replaceAll("\\s","");
In the context of a regex, \s will remove anything that is a space character (including space, tab characters etc). You need to escape the backslash in Java so the regex turns into \\s. Also, since Strings are immutable it is important that you assign the return value of the regex to a.
The most intuitive way of doing this without using literals or regular expressions:
yourString.replaceAll(" ","");
Replace all the spaces in the String with empty character.
String lineWithoutSpaces = line.replaceAll("\\s+","");
Try this:
String str = "Your string with spaces";
str = str.replace(" " , "");
Try:
string output = YourString.replaceAll("\\s","")
s - indicates space character (tab characters etc)
public static String removeSpace(String s) {
String withoutspaces = "";
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != ' ')
withoutspaces += s.charAt(i);
}
return withoutspaces;
}
This is the easiest and most straight forward method to remove spaces from a String.
package com.infy.test;
import java.util.Scanner ;
import java.lang.String ;
public class Test1 {
public static void main (String[]args)
{
String a =null;
Scanner scan = new Scanner(System.in);
System.out.println("*********White Space Remover Program************\n");
System.out.println("Enter your string\n");
a = scan.nextLine();
System.out.println("Input String is :\n"+a);
String b= a.replaceAll("\\s+","");
System.out.println("\nOutput String is :\n"+b);
}
}
Cant you just use String.replace(" ", "");
You can use a regular expression to delete white spaces , try that snippet:
Scanner scan = new Scanner(System.in);
System.out.println(scan.nextLine().replaceAll(" ", ""));
String a="string with multi spaces ";
//or this
String b= a.replaceAll("\\s+"," ");
String c= a.replace(" "," ").replace(" "," ").replace(" "," ").replace(" "," ").replace(" "," ");
//it work fine with any spaces
*don't forget space in sting b
trim.java:30: cannot find symbol
symbol : method substr(int,int)
location: class java.lang.String
b = a.substr(i,160) ;
There is no method like substr in String class.
use String.substring() method.
boolean flag = true;
while(flag) {
s = s.replaceAll(" ", "");
if (!s.contains(" "))
flag = false;
}
return s;
String a="string with multi spaces ";
String b= a.replace(" "," ").replace(" "," ").replace(" "," ").replace(" "," ").replace(" "," ");
//it work fine with any spaces