I have a string:
String x = "10";
Now I want to add . between the numbers and print it like this
1.0
How can I achieve this?
You can split the string into the first character and the rest of the string, and then insert a dot '.' in between, like this:
String res = x.substring(0,1)+"."+x.substring(1);
// ^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^
// the first digit the rest of the string
You can also use replaceAll to do it on longer strings, like this:
String orig = "19,28,37,46";
System.out.println(orig.replaceAll("(\\d)(\\d)", "$1.$2"));
This prints
1.9,2.8,3.7,4.6
Use the DecimalFormat class to better decouple the value and its representation.
If the String is always a 2-digit number :
String result = x.charAt(0) + "." + x.charAt(1);
this function can accepts all number and returns a dotted string, with small touches it can accepts many in other types of data an return data with options
fun getStringWithDot(nums: Int): String {
var str = ""
val istr = nums.toString()
for (ch in istr.indices){
if (ch == istr.length-1){
str += istr.substring(0,1)
}else{
str += istr.substring(ch,ch+1) + "."
}
}
return str
}
public static void main(String args[])
{
Scanner S=new Scanner(System.in);
int arr[];
int number;
number=S.nextInt();
int length=Integer.toString(number).length();
arr=new int[length];
char arr2[];
arr2=new char[length];
int count=0;
char arr3[];
arr3=new char[length];
String Q=Integer.toString(number);
for(int i=0;i<arr3.length;i++)
{
System.out.print(Q.charAt(i)+".");
}
}
Related
I have a string as follows
String str = "AUTHOR01BOOK"
In this string I want to add this number 00001. How can I do that?
I tried concatenate it but the output I got is AUTHOR01BOOK1. My code is not appending zeros. How can I do that?
You can use the print format.
String str="AUTHOR01BOOK";
int num = 000001;
System.out.printf("%s%06d", str, num);
or use the String.format function to store it in a variable:
String myConcat = String.format("%s%05d", str, num);
EDIT:
To answer raju's follow up question about doing this in a loop,
Create a method that will return the formatted string:
static String myConcatWithLoop(String str, int iteration){
return String.format("%s%05d", str, iteration);
}
then call this in your loop:
for (int i = 1; i <= 100; i++) {
System.out.println(myConcatWithLoop(str, i));
}
if you store '000001' in int datatype it will treat as an octal. That is
int a=000001;
System.out.println(a);
Output: 1
It will treat it as OCTAL number
So you cannot store a number beginning with 0 in int as compiler will typecast it. Therefore for that you have to work with Strings only :)
Another approach is use StringBuilder
public class JavaApplication {
public static void main(String[] args) {
JavaApplication ex = new JavaApplication();
String str = "AUTHOR01BOOK";
System.out.println(ex.paddingZero(str));
}
public String paddingZero(String str) {
StringBuilder sb = new StringBuilder();
sb.append(str);
sb.append("00001");
return sb.toString();
}
}
Please try the below code. It not only displays but also changes the string.
StringUtils help us to pad the left zeros.
Number 4 in the leftPad method denotes the number of zeros.
Its not a dynamic solution but it fulfills your need.
import org.apache.commons.lang.StringUtils;
public class Interge {
public static void main(String[] args) {
int i =00001;
String s= i+"";
String result = StringUtils.leftPad(s, 4, "0");
String fnlReslt = "AUTHOR01BOOK"+result;
System.out.println("The String : " + fnlReslt);
}
}
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;
}
}
I want to write a program that would pass an integer and a string to a value-returning method. I know how to do this part, however I need to concatenate the int (which is 2) and the string (which says "bye"), and have it print the string the number of the int. (Example: Bye Bye).
I will respond clarifying the issue as soon as possible.
You can concatenate String with int in Java like this:
String result = "some " + 2;
The string should go first in this "+" operator.
Try this.
static String repeat(int times, String s) {
return IntStream.range(0, times)
.mapToObj(x -> s)
.collect(Collectors.joining(" "));
}
and
System.out.println(repeat(2, "bye"));
// -> bye bye
public String repeatString(String str, int n)
{
if(n<1 || str==null)
return str;
StringBuilder sb = new StringBuilder();
for(int i=0; i<n; i++)
{
sb.append(str);
if(i!=(n-1)) // If not the last word then add space
sb.append(" ");
}
return sb.toString();
}
try this out
private String repeateAndConcateString (int prm_Repeat, String prm_wordToRepeat){
if(prm_Repeat <=0 || prm_wordToRepeat == null){
return "";
}
String temp = "";
for(int i= 1 ; i<=prm_Repeat ; i++){ // loop through the number of times to concatinate.
temp += prm_wordToRepeat; //Concate the String Repeatly 1 to prm_Repeat
}
return temp; // this will return Concatinate String.
}
For string repeat, Apache StringUtils have method repeat.
Or an implementation without externals:
public static String repeat(int n, String s){
StringBuilder sb = new StringBuilder(n * s.length());
while(n--)
sb.append(s);
return sb.toString();
}
Integers can be converted to a string by both references: String.valueOf and Integer.toString. String concatenation works like math addition (+).
I am trying to separate the char from the following examples of inputs:
C450.00
C30
P100
I would like to have the char such as "C" or "P" separated so I can work with them alone,
as well as the "450.00", "30", and "100" separated as ints. What would be the easiest way to do this?
You can split the String with whitespace as delimiter. Afterwards use substring on every part of your string. Now you have the C and the 450.0 as Stings. Finally cast the second part of your substring into an integer and you are done.
to split:
String[] parts = string.split(" ");
to substring:
String first = parts[0].substring(0, 1);
String second = parts[0].substring(1);
If the String are always that format:
char ch = yourString.charAt(0);
Double d = Double.valueOf(yourString.substring(1, yourString.length()));
NOTE: I used a Double because you have dots . in the String. You can convert from double to int easily if you won't have any decimals. But that depends on your needings.
Assuming you know what are you looking for in the given String (eg. You know you are looking for the C character ) , you could use the Regex Pattern : https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
You can use this library org.apache.commons.lang3.StringUtils
http://commons.apache.org/proper/commons-lang/download_lang.cgi
public static String[] split(String str, String separatorChars)
String[] res = StringUtils.split("C450.00 C30 P100", "CP ");
for (String r : res) {
System.out.println(r);
}
I assume the separate 'numbers' are always in this format:
C130
P90
V2.0
that is, a single letter followed by a number (possibly with a floating point).
String input = "C450.00 C30 P100";
// First split the string by a space
String[] parts = input.split(" ");
for (String part : parts) {
// Get the character from the string
char ch = part.charAt(0);
// Get the remains of the string and convert it to a double
double number = Double.parseDouble(part.substring(1));
// Then do something with 'ch' and 'number'
}
If the separate parts possibly have two or more letters in it, e.g. AC130, then you need another approach:
String input = "AC130 AG36 P90";
String[] parts = input.split(" ");
for (String part : parts) {
/* Do some regular expression magic. */
}
See http://www.vogella.com/tutorials/JavaRegularExpressions/article.html.
here some piece of code:
public static void main(String[] args) {
String a = "C450.00 C30 P100";
String letters = "";
String numbers = "";
for (int i = 0; i < a.length(); i++) {
if ((a.charAt(i) + "").matches("\\d|\\.| ")) {
numbers += a.charAt(i);
} else {
letters += a.charAt(i);
}
}
String[] strArray = numbers.split(" ");
int[] numberArray = new int[strArray.length];
for (int i = 0; i < strArray.length; i++) {
numberArray[i] = (int) Double.parseDouble(strArray[i]);
System.out.println(numberArray[i]);
}
System.out.println(letters);
}
the result is numberArray, which contains all numbers as ints.
and letters, which is a String with all letters.
Suppose I have two strings to "join" with a delimiter.
String s1 = "aaa", s2 = "bbb"; // input strings
String s3 = s1 + "-" + s2; // join the strings with dash
I can use s3.split("-") to get s1 and s2. Now, what if s1 or s2 contains dashes? Suppose also that s1 and s2 may contain any ASCII printable and I don't want to use non-printable characters as a delimiter.
What kind of escaping would you suggest in this case?
If I could define the format, delimiters, etc. I would use OpenCSV and use it's defaults.
You could use an uncommon character sequence, such as ;:; as a delimiter instead of a single character.
Here is another working solution, that doesn't use a separator, but that joins the lengths of the strings at the end of the imploded string to be able to re-explode it after:
public static void main(String[] args) throws Exception {
String imploded = implode("me", "and", "mrs.", "jones");
System.out.println(imploded);
String[] exploded = explode(imploded);
System.out.println(Arrays.asList(exploded));
}
public static String implode(String... strings) {
StringBuilder concat = new StringBuilder();
StringBuilder lengths = new StringBuilder();
int i = 0;
for (String string : strings) {
concat.append(string);
if (i > 0) {
lengths.append("|");
}
lengths.append(string.length());
i++;
}
return concat.toString() + "#" + lengths.toString();
}
public static String[] explode(String string) {
int last = string.lastIndexOf("#");
String toExplode = string.substring(0, last);
String[] lengths = string.substring(last + 1).split("\\|");
String[] strings = new String[lengths.length];
int i = 0;
for (String length : lengths) {
int l = Integer.valueOf(length);
strings[i] = toExplode.substring(0, l);
toExplode = toExplode.substring(l);
i++;
}
return strings;
}
Prints:
meandmrs.jones#2|3|4|5
[me, and, mrs., jones]
Why don't you just store those strings in an array and join them with dash each time you want to display them to user?