I have this number: 4200000000000000
I would like to leave only the first 4 digits and last 3 digits:
42000......000
Everything else should be replaced by dots. How I can implement this with some smart algorithm?
Why not use a StringBuilder and the substring method:
public static String foo(long num) {
String numToString = String.valueOf(num);
return new StringBuilder()
.append(numToString.substring(0 , 4))
.append("....")
.append(numToString.substring(numToString.length()-3, numToString.length()))
.toString();
}
When inputted 4200000000000000 it outputs:
4200....000
Or if the input is already a String:
public static String foo(String str) {
return new StringBuilder()
.append(str.substring(0 , 4))
.append("....")
.append(str.substring(str.length()-3, str.length()))
.toString();
}
Parse your number into a string and try this:
int last = 3;
int first = 4;
String number = '4200000000000000';
String start = number.substring(0,first-1);
String end = number.substring(number.length()-last,number.length()-1);
String dots = '';
for(int i = 0; i<number.length()-last-first;i++){
dots = dots + '.';
}
String result = start + dots + end;
You can use something like this,
public class Main {
public static void main(String[] args) {
System.out.println(convert("4200000000000000", 4, 3));
}
static String convert(String number, int firstDigits, int lastDigits) {
String first = number.substring(0, firstDigits);
String middle = number.substring(firstDigits, number.length() - lastDigits).replaceAll("0", ".");
String last = number.substring(number.length() - lastDigits, number.length());
return first + middle + last;
}
}
You could convert it to a char array, alter it, then convert it back into a string
char[] charArray = originalNumber.toCharArray();
for (int i; i < charArray.length; i++) {
if (i <= 4 || i >= charArray.length - 3) {
charArray[i] = ".";
}
}
String outputString = new String(charArray);
This will replace all chars from the 4th char up to the 4th from the end with '.':
String start = "4200000000000000";
System.out.println(start);
String target = start;
if (start.length() > 7) {
target = new StringBuilder()
.append(start.substring(0, 4))
.append(new String(new char[start.length() - 7]).replaceAll(".", "."))
.append(start.substring(start.length() - 3))
.toString();
}
System.out.println(target);
will print
4200000000000000
4200.........000
Using substring method of the String class :
String str = "4200000000000000";
String res = str.substring(0,4)+ str.substring(4,str.length()-3).replaceAll(".", ".") + str.substring(str.length()-3);
If you are using Apache commons library, you can use repeat method to create masking string of specified length and the overlay method of StringUtils class to overlay part of the String :
String str = "4200000000000000";
String mask= StringUtils.repeat('.', str.length()-7);
String res = StringUtils.overlay(str, mask, 4, str.length()-3);
Related
I have a string which looks something like this(the most basic form):
String str = "1.0.0.190"
The str can be something like this as well:
1.11.0.12 or 2.111.1.190 or 1.0.0.0
I want to split the string at the 2nd occurrence of the dot(.). How can I achieve that ?
Output:
String str = "1.0.0.190"
String output = "1.0"
I'd fit the answer to OP's level, so I wouldn't recommend split or regexps to him...
If you need substring to second dot, simply find second dot and cut the string to that position...
public class DotSubstring {
public static void main(String[] args) {
String s = "1.2.3.4";
int secondDotPosition = findSecondDotPosition(s);
if (secondDotPosition > 0) {
System.out.println(s.substring(0, secondDotPosition));
} else {
System.out.printf("ERROR: there is not a 2nd dot in '%s'%n", s);
}
}
private static int findSecondDotPosition(String s) {
int result = -1;
int dotsToFind = 2;
char[] ca = s.toCharArray();
for (int i = 0; i < ca.length; ++i) {
if (ca[i] == '.') --dotsToFind;
if (dotsToFind == 0) return i;
}
return result;
}
}
The problem with split for beginner is, that is accepts regexp, that's why it is escaped in Joop Eggen's answe like this str.split("\\.").
And yes, that can be achieved in one line as user3458271 wrote in a comment same as xyz later in answer, just error checking would be more difficult (for example if there are no 2 dots...).
In one line with substring and indexOf:
String output = str.substring(0,str.indexOf(".",str.indexOf(".")+1));
public static void main(String[] args) {
String input = "2.111.1.190";
String[] out = input.split("\\.");
String output1 = out[0]+"."+out[1];
System.out.println(output1);
String output2 = "";
for(int x=2; x < out.length; x++)
output2 += out[x] +".";
System.out.println(output2);
}
For the other fields too:
String[] halfs = str.split("\\.");
String[] fulls = new String[halfs.length / 2];
for (int i = 0; i < fulls.length; ++i) {
fulls[i] = halfs[2*i] + "." + halfs[2*i + 1];
}
return fulls[0];
The same technique reduced for the first field:
String[] halfs = str.split("\\.", 3);
return halfs[0] + "." + halfs[1];
Simply:
return str.replaceAll("^([^.]*\\.[^.]*)\\..*$", "$1");
I'm building a simple program in Java that finds letters in strings and replaces them with a number, but I'm having trouble finding a method that will allow me to check for the exact specific character. There are plenty for digits and letters in general.
As my for loop stands now, it just replaces the letter everywhere, irregardless of whether it is within the range specified by start and end.
Any help would be appreciated.
String str = "A.A.A.A.A.A.A.A";
int start = 3;
int end = 9;
for (int i = start; i < end; i++) {
if (Character.isLetter(str.charAt(i)) {
str = str.replaceAll("A", "9");
return str;
Expected Output:
A.A.9.9.9.A.A.A
Actual Output:
9.9.9.9.9.9.9.9
In your code, you have
str = str.replaceAll("A", "9");
This will replace all the occurrences of A to 9
Instead of your approach, you should
1.Convert the string to a char array
char[] charArray = str.toCharArray();
2.Then replace each occurrence of character with a number
if (Character.isLetter(charArray[i])){
//Character Found
charArray[i] = '9';
}
3. Convert it back to string using
str = String.valueOf(charArray);
Modified Code:
String str = "A.A.A.A.A.A.A.A";
int start = 3;
int end = 9;
//Converting String to char array
char[] charArray = str.toCharArray();
for (int i = start; i < end; i++) {
if (Character.isLetter(charArray[i])){
//Character Found
charArray[i] = '9';
}
}
//Converting Back to String
str = String.valueOf(charArray);
System.out.println(charArray);
System.out.println(str);
Compare for character equality and then use string builder to replace the specified character
//Use of StringBuffer preferred over String as String are immutable
StringBuilder sb = new StringBuilder(str);
// -1 to start as index start from 0
for (int i = start-1; i < end; i++) {
char currentChar = currentString.charAt(i);
if (currentChar == "A") {
sb.setCharAt(i, '9');
}
}
return sb.toString();
I'd do it that way. Cut out the string to isolate the part you want to act on, do your replace ans stitch it all back together :
String str = "A.A.A.A.A.A.A.A";
int startIndex = 3;
int endIndex = 9;
String beginning = str.substring(0, startIndex);
String middle = str.substring(startIndex, endIndex);
String end = str.substring(endIndex);
middle = middle.replaceAll("A", "9");
String result = beginning + middle + end;
System.out.println(result);
Prints out :
A.A.9.9.9.A.A.A
EDIT:
As suggested in the comments, you could do it in one line
String str = "A.A.A.A.A.A.A.A";
int startIndex = 3;
int endIndex = 9;
String result =
str.substring(0, startIndex) +
str.substring(startIndex, endIndex).replaceAll("A", "9") +
str.substring(endIndex);
Here is an example using substrings to let you choose what portion of the string you want to test
int start = 3;
int end = 9;
String str = "A.A.A.A.A.A.A.A";
String startStr = str.substring(0,start);
String endStr = str.substring(end);
String newStr="";
char temp=' ';
for (int i = start; i < end; i++) {
temp = str.charAt(i);
if (temp=='A')
newStr+="9";
else
newStr += temp;
}
return(startStr + newStr + endStr);
You are replacing all the match found in the string and not specifying the index that needs to be replaced.
Use the StringBuffer replace method like below:
public static void main(String[] args) {
String str = "AAAAAAAA";
int start = 3;
int end = 9;
str = replaceBetweenIndexes(str, start, end, "9"); // AAA999AA
str = replaceBetweenIndexes("ABCD6EFG", start, end, "3"); // ABC363FG
}
public static String replaceBetweenIndexes(String str, int start, int end, String replaceWith) {
StringBuffer strBuf = new StringBuffer(str);
for (int i = start; i < end; i++) {
if (Character.isLetter(strBuf.charAt(i)) {
strBuf.replace(i, i+1, replaceWith);
}
}
return strBuf.toString();
}
Given a string as input, return the string with its last 2 chars swapped. And, if the string has less than 2 chars, do nothing and return the input string.
Here is the code I wrote so far:
public class SwapLastChars {
static String testcase1 = "Hello";
public static void main(String args[]) {
SwapLastChars testInstance = new SwapLastChars();
String result = testInstance.swap(testcase1);
System.out.println(result);
}
public String swap(String str1) {
String str = "";
int length = str1.length();
char last = str1.charAt(length - 1);
char l = str1.charAt(length - 2);
if (length == 1)
return str1;
for (int i = 0; i < str1.length() - 2; i++) {
str = str + str1.charAt(i);
}
str = str + last + l;
return str;
}
}
Problem is in my test cases,any help?
Testcase Pass/Fail Parameters Actual Output Expected Output
1 pass 'aabbccdd' aabbccdd aabbccdd
2 fail 'A' null A
3 pass 'hello' helol helol
If you pass "A" you'll get StringIndexOutOfBoundsException rather than null. Unless you suppress it in a catch clause and return null.
Quick fix. Move the length check to start of the method. That should solve your issue.
public class SwapLastChars {
static String testcase1 = "A";
public static void main(String args[]) {
SwapLastChars testInstance = new SwapLastChars();
String result = testInstance.swap(testcase1);
System.out.println(result);
}
public String swap(String str1) {
if(str1 == null || str1.length() < 2) { //Move here
return str1;
}
String str = "";
int length = str1.length();
char last = str1.charAt(length - 1);
char l = str1.charAt(length - 2);
for(int i = 0; i < str1.length() - 2; i++) {
str = str + str1.charAt(i);
}
str = str + last + l;
return str;
}
}
You should check for length at the very beginning of your function.
public String swap(String str1){
String str="";
int length=str1.length();
if (length <=2)
return str1;
char last=str1.charAt(length-1);
char l=str1.charAt(length-2);
for(int i=0;i<str1.length()-2;i++)
{
str=str+str1.charAt(i);
}
str=str+last+l;
return str;
}
I know this has already been answered, but I feel OPs swap method can be simplified by using a StringBuilder:
public static String swap(String word) {
//Answer by Syam
if (word == null || word.length() < 2) {
return word;
}
//Create new StringBuilder
StringBuilder s = new StringBuilder(word);
//Get second last char
char c = s.charAt(s.length() - 2);
//Replace second last char with last char
s.setCharAt(s.length() - 2, s.charAt(s.length() - 1));
//replace last char with stored char
s.setCharAt(s.length() - 1, c);
return s.toString();
}
Run:
System.out.println(swap("aabbccdd"));
System.out.println(swap("A"));
System.out.println(swap("hello"));
Output:
aabbccdd
A
helol
And here is why
I have a String with name str.
str = "hi john";
Now I want to set j char to g. How can I do that?
You can't modify a String directly, but you can either use a StringBuilder:
str = "hi john";
StringBuilder sb = new StringBuilder(str);
sb.setCharAt(3,'g');
str = sb.toString();
.. or convert it to a char[] and back
str = "hi john";
char[] chars = str.toCharArray();
chars[3] = 'g';
str = new String(chars);
Two ways :
a. This will replace all occurances of 'j' with 'g'.
String str1 = "hi john";
System.out.println(str1); // prints - hi john
String str2 = str1.replace('j', 'g');
System.out.println(str2); // prints - hi gohn
b. If you wish to change the 'j' character only at one location in the string, you may want to do like this.
String str4 = replaceCharAt("hi john", 3,'g');
public static String replaceCharAt(String str1, int pos, char c) {
StringBuffer buf = new StringBuffer(str1);
buf.setCharAt(pos,c);
return buf.toString( );
}
// Here : pos = 3, char = 'g' and str1 = "hi john"
str = str.replace('j', 'g'); should do it for you.
str.replace('j','g');
as this java api shows
http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#replace(char, char)
you can do like this
String str ="hi john"
syso(str.replace('j','g'));
Output will be hi gohn
You can use the substring. Look at :http://download.oracle.com/javase/tutorial/java/data/manipstrings.html
You can use something like this:
public static String replace(String _text, String _searchStr, String _replacementStr) {
// String buffer to store str
StringBuffer sb = new StringBuffer();
// Search for search
int searchStringPos = _text.indexOf(_searchStr);
int startPos = 0;
int searchStringLength = _searchStr.length();
// Iterate to add string
while (searchStringPos != -1) {
sb.append(_text.substring(startPos, searchStringPos)).append(_replacementStr);
startPos = searchStringPos + searchStringLength;
searchStringPos = _text.indexOf(_searchStr, startPos);
}
// Create string
sb.append(_text.substring(startPos,_text.length()));
return sb.toString();
}
public static int indexOf(String sb, String str, int start){
int index = -1;
if((start>=sb.length() || start<-1) || str.length()<=0) return index;
char[] tofind = str.toCharArray();
outer: for(;start<sb.length(); start++){
char c = sb.charAt(start);
if(c==tofind[0]){
if(1==tofind.length) return start;
inner: for(int i = 1; i<tofind.length;i++){ // start on the 2nd character
char find = tofind[i];
int currentSourceIndex = start+i;
if(currentSourceIndex<sb.length()){
char source = sb.charAt(start+i);
if(find==source){
if(i==tofind.length-1){
return start;
}
continue inner;
} else {
start++;
continue outer;
}
} else {
return -1;
}
}
}
}
return index;
}
String s;
int i = str.indexOf('j');
s = str.subString(0, i) + 'g' + str.subString(i + 1, str.length() - 1);
I did not find anywhere an answer.. If i have: String s = "How are you"?
How can i split this into two strings, so first string containing from 0..s.length()/2 and the 2nd string from s.length()/2+1..s.length()?
Thanks!
This should do:
String s = "How are you?";
String first = s.substring(0, s.length() / 2); // gives "How ar"
String second = s.substring(s.length() / 2); // gives "e you?"
String.substring(int i) with one argument returns the substring beginning at position i
String.substring(int i, int j) with two arguments returns the substring beginning at i and ending at j-1.
(Note that if the length of the string is odd, second will have one more character than first due to the rounding in the integer division.)
String s0 = "How are you?";
String s1 = s0.subString(0, s0.length() / 2);
String s2 = s0.subString(s0.length() / 2);
So long as s0 is not null.
EDIT
This will work for odd length strings as you are not adding 1 to either index. Surprisingly it even works on a zero length string "".
You can use 'substring(start, end)', but of course check if string isn't null before:
String first = s.substring(0, s.length() / 2);
String second = s.substring(s.length() / 2);
http://www.roseindia.net/java/beginners/SubstringExample.shtml
And are you expecting string with odd length ? in this case you must add logic to handle this case correctly.
Here's a method that splits a string into n items by length. (If the string length can not exactly be divided by n, the last item will be shorter.)
public static String[] splitInEqualParts(final String s, final int n){
if(s == null){
return null;
}
final int strlen = s.length();
if(strlen < n){
// this could be handled differently
throw new IllegalArgumentException("String too short");
}
final String[] arr = new String[n];
final int tokensize = strlen / n + (strlen % n == 0 ? 0 : 1);
for(int i = 0; i < n; i++){
arr[i] =
s.substring(i * tokensize,
Math.min((i + 1) * tokensize, strlen));
}
return arr;
}
Test code:
/**
* Didn't use Arrays.toString() because I wanted to have quotes.
*/
private static void printArray(final String[] arr){
System.out.print("[");
boolean first = true;
for(final String item : arr){
if(first) first = false;
else System.out.print(", ");
System.out.print("'" + item + "'");
}
System.out.println("]");
}
public static void main(final String[] args){
printArray(splitInEqualParts("Hound dog", 2));
printArray(splitInEqualParts("Love me tender", 3));
printArray(splitInEqualParts("Jailhouse Rock", 4));
}
Output:
['Hound', ' dog']
['Love ', 'me te', 'nder']
['Jail', 'hous', 'e Ro', 'ck']
Use String.substring(int), and String.substring(int, int) method.
int cutPos = s.length()/2;
String s1 = s.substring(0, cutPos);
String s2 = s.substring(cutPos, s.length()); //which is essentially the same as
//String s2 = s.substring(cutPos);
I did not find anywhere an answer.
The first place you should always look is at the javadocs for the class in question: in this case java.lang.String. The javadocs
can be browsed online on the Oracle website (e.g. at http://download.oracle.com/javase/6/docs/api/),
are included in any Sun/Oracle Java SDK distribution,
are probably viewable in your Java IDE, and
and be found using a Google search.
public int solution(final String S, final int K) {
int splitCount = -1;
final int count = (int) Stream.of(S.split(" ")).filter(v -> v.length() > K).count();
if (count > 0) {
return splitCount;
}
final List<String> words = Stream.of(S.split(" ")).collect(Collectors.toList());
final List<String> subStrings = new ArrayList<>();
int counter = 0;
for (final String word : words) {
final StringJoiner sj = new StringJoiner(" ");
if (subStrings.size() > 0) {
final String oldString = subStrings.get(counter);
if (oldString.length() + word.length() <= K - 1) {
subStrings.set(counter, sj.add(oldString).add(word).toString());
} else {
counter++;
subStrings.add(counter, sj.add(word).toString());
}
} else {
subStrings.add(sj.add(word).toString());
}
}
subStrings.forEach(
v -> {
System.out.printf("[%s] and length %d\n", v, v.length());
}
);
splitCount = subStrings.size();
return splitCount;
}
public static void main(final String[] args) {
final MessageSolution messageSolution = new MessageSolution();
final String message = "SMSas5 ABC DECF HIJK1566 SMS POP SUV XMXS MSMS";
final int maxSize = 11;
System.out.println(messageSolution.solution(message, maxSize));
}