and thank you for helping me.
So my question is i need a code that asks you for a String like "1234 567" (input), then returns the string numbers like "1 2 3 4 5 6 7" (output) once more
my current code is:
public class StringComEspaços {
public static String formatNumberWithSpaces(String inputString) {
String outputString = "222";
return outputString;
}
public static void main(String[] args) {
System.out.println(formatNumberWithSpaces("123 222 2222"));
}
}
thanks for the help, and sorry for bad english :).
There are many possible ways to solve your problem.
You can do it in an OO way with StringBuilder:
public static String formatNumberWithSpaces(String inputString) {
StringBuilder output = new StringBuilder();
for (char c : inputString.toCharArray()) // Iterate over every char
if (c != ' ') // Get rid of spaces
output.append(c).append(' '); // Append the char and a space
return output.toString();
}
Which you can also do with a String instead of the StringBuilder by simply using the + operator instead of the .append() method.
Or you can do it a more "modern" way by using Java 8 features - which in my opinion is fun doing, but not the best way - e.g. like this:
public static String formatNumberWithSpaces(String inputString) {
return Arrays.stream(input.split("")) // Convert to stream of every char
.map(String::trim) // Convert spaces to empty strings
.filter(s -> !s.isEmpty()) // Remove empty strings
.reduce((l, r) -> l + " " + r) // build the new string with spaces between every character
.get(); // Get the actual string from the optional
}
Just try something that works for you.
Try out this function:
public static String formatNumberWithSpaces(String inputString){
String outputString = ""; //Declare an empty String
for (int i = 0;i < inputString.length(); i++){ //Iterate through the String passed as function argument
if (inputString.charAt(i) != ' '){ //Use the charAt function which returns the char representation of specified string index(i variable)
outputString+=inputString.charAt(i); //Same as 'outputString = outputString + inputString.charAt(i);'. So now we collect the char and append it to empty string
outputString+=' '; //We need to separate the next char using ' '
} //We do above instruction in loop till the end of string is reached
}
return outputString.substring(0, outputString.length()-1);
}
Just call it by:
System.out.println(formatNumberWithSpaces("123 222 2222"));
EDIT:
Or if you want to ask user for input, try:
Scanner in = new Scanner(System.in);
System.out.println("Give me your string to parse");
String input = in.nextLine(); //it moves the scanner position to the next line and returns the value as a string.
System.out.println(formatNumberWithSpaces(input)); // Here you print the returned value of formatNumberWithSpaces function
Don't forget to import, so you will be able to read user input :
import java.util.Scanner;
There are various ways to read input from the keyboard, the java.util.Scanner class is one of them.
EDIT2:
I changed:
return outputString;
..to: return outputString.substring(0, outputString.length()-1);
Just because outputString+=' '; was also appending empty space at the end of string, which is useless. Didn't add an if inside for loop which wouldn't add space when last char is parsed, just because of its low performance inside for loop.
use this code.
public class StringComEspaços {
public static void main(String[] args) {
System.out.println(formatNumberWithSpaces("123 222 2222"));
}
private static String formatNumberWithSpaces(String string) {
String lineWithoutSpaces = string.replaceAll("\\s+", "");
String[] s = lineWithoutSpaces.split("");
String os = "";
for (int i = 0; i < s.length; i++) {
os = os + s[i] + " ";
}
return os;
}
}
Related
I want to reverse a string.
input: Computer;
This input contains 4 whitespaces in the beginning of the word 'computer'.I want to include these 4 whitespaces in the beginning of the reversed string also.So,the program should include all the whitespaces I put at the beginning while taking the reverse too(I put 4 whitespaces as an example only).
output:" retupmoc";
I am attaching my code here.
package BasicTesting;
import java.util.*;
public class Corrected_StringRev {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in); //System.in is a standard input stream
System.out.print("Enter a string: ");
String str= sc.nextLine();
String reversed = reverseString( str );
System.out.println( reversed );
}
public static String reverseString( String newString ) {
char ch[]=newString.toCharArray();
String rev="";
for(int i=ch.length-1;i>=0;i--){
rev+=ch[i];
}
return rev;
}
}
How can I change this code to include the above requirement.Please,rewrite the code.Hope ypu will help.Thanks in adavance!
The logic is simple:
Traverse the start of the string and add whitespaces to rev until you meet the first non-whitespace
Do your string reversal and stop before the whitespace section begins
public static String reverseString(String newString) {
char ch[] = newString.toCharArray();
String rev = "";
int nWhitespace;
for (nWhitespace = 0; nWhitespace < ch.length; nWhitespace++) {
if (!Character.isWhitespace(ch[i]) {
break;
}
rev += ch[i];
}
for(int i = ch.length - 1; i >= nWhitespace; i--){
rev += ch[i];
}
return rev;
}
By the way, you can improve your code by using StringBuilder instead of +=.
Here instead of keeping a count and then adding it, we will be checking if the character we are at currently in the string is a whitespace character. If yes, we add a space to our string builder.
As soon as we come across a non-whitespace character, we break out of the loop.
strB.append(new StringBuilder(inputString.trim()).reverse().toString());
return strB.toString();
What this code does is:
Take string inputString and trim it (remove trailing and leading whitespaces.
Creates a new (anonymous) object of a StringBuilder and reverses it.
Convert it into a string to append it to our original StringBuilder strB after the whitespaces.
Finally, we convert it into String and return it.
Some tips:
I will be using StringBuilder as it is mutable so saves space and also it contains a function to reverse it directly.
You should not call the length function of string in the loop as it will call it for every loop. Better to store the value in a variable and use that variable in the loop.
public static String reverseString(String inputString) {
StringBuilder strB = new StringBuilder();
int len = inputString.length();
for (int i = 0; i<len && inputString.charAt(i) == ' '; i++) {
strB.append(" ");
}
strB.append(new StringBuilder(inputString.trim()).reverse().toString());
return strB.toString();
}
public class StringDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
String name = "String";
char[] c = name.toCharArray();
for (char ch : c) {
System.out.print(ch);
System.out.print(",");
}
}
}
This gives me output as
S,t,r,i,n,g,
I don't want that last comma, how to get output as S,t,r,i,n,g
You can also do it on a higher level without writing your own loop. It's not faster or anything, but the code is more clear about what it's doing: "Split my string into characters and join it back together, separated by commas!" ...
String name = "String";
String separated = String.join(",", name.split(""));
System.out.println(separated);
EDIT: String.join() is available from Java 1.8 and up.
I would personally use a StringBuilder for this task.
What you need, is to apply some logic that can distinguish whether or not a comma is needed. You loop through the characters just like you did and you always append a comma before the next character, except on the first iteration.
Example:
public static void main(String[] args) {
String test = "String";
StringBuilder sb = new StringBuilder();
for (char ch : test.toCharArray()) {
if (sb.length() != 0) {
sb.append(",");
}
sb.append(ch);
}
System.out.println(sb.toString());
}
Output:
S,t,r,i,n,g
Another way without StringBuilder and using just a traditional for loop, but using the same logic:
public static void main(String[] args) {
String test = "String";
char[] chars = test.toCharArray();
for (int i = 0; i < chars.length; i++) {
if (i != 0) {
System.out.print(",");
}
System.out.print(chars[i]);
}
}
Output:
S,t,r,i,n,g
Sure, but for this you need a for loop based on the length of c, other solutions are not as straight IMHO:
String name="String";
char[] c = name.toCharArray();
for (int i = 0; i < c.length; i++){
char ch = c[i];
System.out.print(ch);
if( i != c.length -1 ){
System.out.print(",");
}
}
Some additional 2 Cents:
You can stream the character int values, map them to a List<String> where each element is a single char as String and finally use String.join(..., ...) in order to get the desired result, a comma separated String of all the characters in the original String:
public static void main(String[] args) {
// take an example String
String name = "Stringchars";
// make a list of characters as String of it by streaming the chars
List<String> nameCharsAsString = name.chars()
// mapping each one to a String
.mapToObj(e -> String.valueOf((char) e))
// and collect them in a list
.collect(Collectors.toList());
// then join the elements of that list to a comma separated String
String nameCharsCommaSeparated = String.join(",", nameCharsAsString);
// and print it
System.out.println(nameCharsCommaSeparated);
}
Running this code results in the following output:
S,t,r,i,n,g,c,h,a,r,s
This is just another possibility of getting your desired result, it is not necessarily the best solution.
You can use Stream to do that. Please check below,
String result = Arrays.stream(name.split("")).collect(Collectors.joining(","));
Output:
S,t,r,i,n,g
I'm trying to print out a string with spaces on either side of each char in the string
so if I have
String s = "abcde"
it would create something like this
a b c d e
with a space before the first char and three between each char.
I just haven't been able to find a way to do this with my knowledge.
Update
Updated requirement:
I failed to realize that I need something that add one place in front
of the first term and then 3 spaces between each term.
_0___0___0___0___0_ for example.
For the updated requirement, you can use yet another cool thing, String#join.
public class Main {
public static void main(String[] args) {
String s = "abcde";
String result = "_" + String.join("___", s.split("")) + "_";
System.out.println(result);
}
}
Output:
_a___b___c___d___e_
Original answer
There can be so many ways to do it. I find it easier to do it using Regex:
public class Main {
public static void main(String[] args) {
String s = "abcde";
String result = s.replaceAll(".", " $0 ");
System.out.println(result);
}
}
Output:
a b c d e
The Regex, . matches a single character and $0 replaces this match with space + match + space.
Another cool way is by using Stream API.
import java.util.Arrays;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
String s = "abcde";
String result = Arrays.stream(s.split(""))
.map(str -> " " + str + " ")
.collect(Collectors.joining());
System.out.println(result);
}
}
Output:
a b c d e
A super simple example, that doesn't handle a multitude of potential input scenarios.
public static void main(String[] args)
{
String s = "abcde";
for (int i = 0; i < s.length(); ++i) {
System.out.print("_" + s.charAt(i));
}
System.out.println("_");
}
NOTE: used an underscore rather than a space in order to allow visual check of the output.
Sample output:
_a_b_c_d_e_
Rather than direct output, one could use a StringBuilder and .append to a builder instead, for example.
Using StringBuilder:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); ++i) {
sb.append('_').append(s.charAt(i));
}
sb.append('_');
System.out.println(sb.toString());
Based on a comment where the desired output is slightly different (two internal spaces, one leading and trailing space), this suggests an alternative approach:
public static String addSpace(String inp) {
StringBuilder sB = new StringBuilder();
String string = inp.trim();
String div = "___"; // spaces, or whatever
sB.append('_'); // add leading space
for(int index = 0; index < string.length(); ++index) {
sB.append(string.charAt(index))
.append(div); // two spaces
}
sB.setLength(sB.length() - (div.length() - 1) );
return (sB.toString());
}
NOTE: again using an underscore to allow for easier debugging.
Output when div is set to 3 underscores (or spaces):
_0___0___0___1___0___1___1___0_
You can define an empty string : result = “”;
Then go through the string you want to print with foreach loop With the function toCharArray()
(char character : str.toCharArray())
And inside this loop do ->
result += “ “ + character;
String result = s.chars().mapToObj(
Character::toString
).collect(Collectors.joining(" "));
Similar to the loop versions, but uses a Stream.
Another one liner to achieve this, by splitting the String into String[] of characters and joining them by space:
public class Main {
public static void main(String[] args) {
String s = "abcde";
System.out.println(" " + String.join(" ", s.split("")) + " ");
}
}
Output:
a b c d e
Edit:
The above code won't work for strings with Unicode codepoints like "👦ab😊", so instead of splitting on empty string, the split should be performed on regex: "(?<=.)".
public class Main {
public static void main(String[] args) {
String s = "abcde";
System.out.println(" " + String.join(" ", s.split("(?<=.)")) + " ");
}
}
Thanks to #saka1029 for pointing this out.
You can use Collectors.joining(delimiter,prefix,suffix) method with three parameters:
String s1 = "abcde";
String s2 = Arrays.stream(s1.split(""))
.collect(Collectors.joining("_+_", "-{", "}-"));
System.out.println(s2); // -{a_+_b_+_c_+_d_+_e}-
See also: How to get all possible combinations from two arrays?
I need help with decompressing method. I have a working Compress method. Any suggestions as far as what I need to consider? Do I need parseInt or else....? Appreciate the advice. Here is what I have so far. If s = "ab3cca4bc", then it should return "abbbccaaaabc", for example of decompress.
class RunLengthCode {
private String pText, cText;
public RunLengthCode () {
pText = "";
cText = "";
}
public void setPText (String newPText) {
pText = newPText;
}
public void setCText (String newCText) {
cText = newCText;
}
public String getPText () {
return pText;
}
public String getCText () {
return cText;
}
public void compress () { // compresses pText to cText
String ans = "";
for (int i = 0; i < pText.length(); i++) {
char current = pText.charAt(i);
int cnt = 1;
String temp = "";
temp = temp + current;
while (i < pText.length() - 1 && (current == pText.charAt(i + 1))) {
cnt++;
i++;
temp = temp + current;
}
if (cnt > 2) {
ans = ans + current;
ans = ans + cnt;
}
else
ans = ans + temp;
setCText(ans);
}
}
public void decompress () {
}
}
public class {
public static void main(String [] args) {
Scanner in = new Scanner(System.in);
RunLengthCode myC = new RunLengthCode();
String pText, cText;
System.out.print("Enter a plain text consisting of only lower-case alphabets and spaces:");
pText = in.nextLine();
myC.setPText(pText);
myC.compress();
System.out.println(pText+" => "+myC.getCText());
System.out.print("Enter a compressed text consisting of only lower-case alphabets, spaces and digits:");
cText = in.nextLine();
myC.setCText(cText);
myC.decompress();
System.out.println(cText+" => "+myC.getPText());
}
}
You could create break the string into regx groups and combine them.
The following pattern works
(([A-Za-z]+[\d]*))
This will break your string "ab3cca4bc" into groups of
"ab3", "cca4", "bc"
So in a loop if the last character is a digit, you could multiply the character before it that many times.
Ok, so you've got an input string that looks like ab3cca4bc
1.) Loop over the length of the input String
2.) During each loop iteration, use the String.charAt(int) method to pick up the individual character
3.) The Character class has an isDigit(char) function that you can use to determine if a character is a number or not. You can then safely use Integer.parseInt(String) (you can use myChar+"" to convert a char into a String)
4.) If the char in question is a number, then you'll need to have an inner loop to repeat the previous character the correct number of times. How will you know what the last character was? Maybe have a variable that's instantiated outside the loop that you update each time you add a character on the end?
I'm trying to create a method that will accept 2 strings as arguments. The first string will be a phrase, the second also a prhase. What I want the method to do is to compare both strings for matching chars. If string 2 has a char that is found in string 1 then replace string 2's instance of the char with an underscore.
Example:
This is the input:
phrase1 = "String 1"
phrase2 = "Strone 2"
The output string is called newPhrase and it will have the string built from the underscores:
newPhrase = "___one 2"
Its not working for me I am doing something wrong.
public class DashedPhrase
{
public static void main(String[] args)
{
dashedHelp("ABCDE","ABDC");
}
public static String dashedHelp(String phrase1, String phrase2)
{
String newPhrase = "_";
for(int i = 0; i < phrase.length(); i++)
{
if(phrase.charAt(i) == phrase2.charAt(i))
{
newPhrase.charAt(i) += phrase2.charAt(i);
}
}
System.out.print(newPhrase);
return newPhrase;
}
}
To make it easier for you to understand, you can use StringBuilder and its method setCharAt().
Notice the i < phrase1.length() && i < phrase2.length() in the condition for the for loop. This is to make sure you don't get any ArrayIndexOutOfBounds exception.
public static void main(String[] args)
{
System.out.println("ABCDE");
System.out.println("ABDC");
dashedHelp("ABCDE","ABDC");
System.out.println();
System.out.println();
System.out.println("String 1");
System.out.println("Strone 2");
String phrase1 = "String 1";
String phrase2 = "Strone 2";
dashedHelp(phrase1, phrase2);
}
public static String dashedHelp(String phrase1, String phrase2)
{
StringBuilder newPhrase = new StringBuilder(phrase1);
for(int i = 0; i < phrase1.length() && i < phrase2.length(); i++)
{
if(phrase1.charAt(i) == phrase2.charAt(i))
{
newPhrase.setCharAt(i, '_');
}
}
System.out.print(newPhrase);
return newPhrase.toString();
}
Output:
ABCDE
ABDC
__CDE
String 1
Strone 2
___i_g_1
newPhrase.charAt(i) doesn't let you replace a character, it just returns it. Java's Strings are immutable. I you want to change it you should use StringBuilder. Look into the replace(int start, int end, String str) method.
Since you need to return a string that has the same length as phrase2, you need to iterate over each character of phrase2, and replace the matching characters of both phrases. And, of course, if phrase2 is longer than phrase1, you need to include the remaining characters in the answer. You can try this:
public static String dashedHelp(String phrase1, String phrase2) {
String ans = "";
String subChar = "_";
int i;
for(i = 0; i<phrase2.length(); i++) {
if(i<phrase1.length() && phrase1.charAt(i) == phrase2.charAt(i))
ans += subChar;
else
ans += phrase2.charAt(i);
}
return ans;
}
Hope it helps
Of course, if you need to output phrase1 with underscores in the places where phrase2 has equal characters, you can interchange phrase2 with phrase1 in the above code.
Testing it
The complete class would look like this:
public class MyClass {
public static String dashedHelp(String phrase1, String phrase2) {
// The method code goes here
}
public static void main(String[] args) {
System.out.println(dashedHelp("String 1", "Strone 2"));
}
}
The output of this program is ___o_e_2. This matches (approximately) your desired output.
The code in the example won't even compile.
newPhrase.charAt(i) += phrase2.charAt(i);
That's a bad assignment. It's the same as writing
newPhrase.charAt(i) = newPhrase.charAt(i) + phrase2.charAt(i);
but the expression on the left side of the '=' isn't something to which you can properly assign a value.