Replacing last 4 characters with a "*" - java

I have a string and I need to replace the last 4 characters of the string with a "*" symbol. Can anyone please tell me how to do it.

A quick and easy method...
public static String replaceLastFour(String s) {
int length = s.length();
//Check whether or not the string contains at least four characters; if not, this method is useless
if (length < 4) return "Error: The provided string is not greater than four characters long.";
return s.substring(0, length - 4) + "****";
}
Now all you have to do is call replaceLastFour(String s) with a string as the argument, like so:
public class Test {
public static void main(String[] args) {
replaceLastFour("hi");
//"Error: The provided string is not greater than four characters long."
replaceLastFour("Welcome to StackOverflow!");
//"Welcome to StackOverf****"
}
public static String replaceLastFour(String s) {
int length = s.length();
if (length < 4) return "Error: The provided string is not greater than four characters long.";
return s.substring(0, length - 4) + "****";
}
}

The simplest is to use a regular expression:
String s = "abcdefg"
s = s.replaceFirst(".{4}$", "****"); => "abc****"

Maybe an example would help:
String hello = "Hello, World!";
hello = hello.substring(0, hello.length() - 4);
// hello == "Hello, Wo"
hello = hello + "****";
// hello == "Hello, Wo****"

public class Model {
public static void main(String[] args) {
String s="Hello world";
System.out.println(s.substring(0, s.length()-4)+"****");
}
}

You can use substring for this.
String str = "mystring";
str = str.substring(0,str.length()-4);
str = str + "****";
So substring takes two parameter.
substring(beginIndex, endIndex);
So, if you call a substring method in a string, It creates a new String that begins from beginIndex inclusive and endIndex exclusive. For example:
String str = "roller";
str = str.substring(0,4);
System.out.Println("str");
OUTPUT :
roll
so it starts from the beginIndex until the endIndex - 1.
If you want to know more about substring, visit http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html
Hope this helps.

Here is my solution for keeping only the first 3 original characters
/**
* #param s
* #return first 3 Characters of s, filled up with * to the Length of s, or s if shorter than 4 Char
*/
static String replaceLastChars(String s) {
if (StringUtils.isBlank(s) || s.length() < 4) {
return s;
}
return StringUtils.rightPad(s.substring(0, 3), s.length(), '*');
}
And the corresponding TestCase
#Test
public void testReplace() {
assertThat(replaceLastChars(null)).isNull();
assertThat(replaceLastChars("")).isEqualTo("");
assertThat(replaceLastChars("abc")).isEqualTo("abc");
assertThat(replaceLastChars("abcdfg")).isEqualTo("abc***");
}

Using Javascript slice will solve your problem easy as slice.... check this out.
var str = "12345678";
console.log(str.slice(0, -4) + "XXXX");

Related

Is there a better way to write s.substring so my code doesn't fail when having one character

When writing 'Hello' as my string, my output is 'He'. The same when writing 'He' as my string, my output is also 'He'. I have added a piece of code that states when the string is bigger then one character, then it should just print the character itself.
This seems very basic but somehow I get an error when only giving one character such as 'H' as my string. It says: String index out of range: 2.
public static void main(String[] args) {
String s = "o";
String s1 = s.substring(0,2);
if (s.length() >= 1 )
{
System.out.println(s);
}
else
{
System.out.println(s1);
}
}
}
Alternative:
s.substring(0, Math.min(2, s.length()))
You need to check this before calling String.substring(). You can use a ternary operator ? : to make the code shorter:
String s = "a"
String o = s.substring(0, s.length() > 2 ? 2 : s.length());
System.out.println(o); // a
When the string only have one character, you still run the String s1 = s.substring(0,2); , which will try to access the second character, and you get an out of range exception.
You could write your code as:
String s = "o";
String s1 = s;
if (s.length() > 2) {
s1 = s.substring(0,2);
}
System.out.println(s1);
That way you only make a substring of s when it has more than 2 characters.
Please check the below code
class test {
public static void main(String[] args) {
String s = "o";
if (s.length() <= 1) {
System.out.println(s);
} else {
String s1 = s.substring(0, 2);
System.out.println(s1);
}
}
}
We cannot have a substring whose length is greater than the provided string's length, and hence those errors.

Cannot convert int to string in Java

I get an error: cannot convert int to string in Java
Script simply extracts a 'hidden' word inside a string by taking the first 2 letters, mid letter and last 2 letters
Here's my code:
package hello;
import java.util.*;
public class hello {
public static String extract(String input) {
if (input.length()>5) {
int len = input.length();
return input.charAt(0) + input.charAt(1) + input.charAt(len/2)+ input.charAt(len-2)+ input.charAt(len-1);
}
}
public static void main(String[] args) {
System.out.println("Enter a word:");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String output = extract(input);
System.out.println(output);
}
}
return input.charAt(0) + input.charAt(1) + input.charAt(len/2)+ input.charAt(len-2)+ input.charAt(len-1)
char is an int type. If you add together a bunch of characters, you get an int, not a string.
On the other hand, if you add a string to a char, or to another string, then they are concatenated into another string:
return input.substring(0,2) + input.charAt(len/2) + input.substring(len-2);
Edit
Your method currently only returns if input.length()>5. If the length is 5 or less, your method doesn't know what it should return, so the code will not compile.
If you know what your method should return in this case, add an extra return after your if block.
public static String extract(String input) {
int len = input.length();
if (len >= 5) {
return input.substring(0,2) + input.charAt(len/2) + input.substring(len-2);
}
return input; // must return something if the length was less than 5.
}
Alternatively, you might want to throw an exception if your string is too short.
When you use + between two chars it considered like you sum two integer for example :
'a' + 'b'
Is equivalent to :
97 + 98
In your case you can use String.copyValueOf to create a String from your chars.
return String.copyValueOf(new
char[] {
input.charAt(0), input.charAt(1), input.charAt(len / 2),
input.charAt(len - 2), input.charAt(len - 1)
}
);
This will create a String from this chars.
Your method still need to return a default value if your condition is not correct.
public static String extract(String input) {
if (input.length() > 5) {
int len = input.length();
return String.copyValueOf(new
char[] {
input.charAt(0), input.charAt(1), input.charAt(len / 2),
input.charAt(len - 2), input.charAt(len - 1)
}
);
}
return "";//if the condition is wrong return empty string or null
}

Reverse string printing method

I am trying to solve the following problem but how do write the method that accepts String as an argument?
Write a method named printReverse that accepts a String as an
argument and prints the characters in the opposite order. If the empty
string is passed as an argument, the method should produce no output.
Be sure to write a main method that convincingly demonstrates your
program in action. Do not use the reverse method of the
StringBuilder or StringBuffer class!
So far I have solved it in a easier manner:
import java.util.Scanner;
class ReverseString {
public static void main(String args[]) {
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to reverse");
original = in.nextLine();
int length = original.length();
for (int i = length - 1; i >= 0; i--)
reverse = reverse + original.charAt(i);
System.out.println("Reverse of entered string is: " + reverse);
}
}
I highly recommend you to go through a basic tutorial.
You can simply do:
private static String myReverse(String str) {
String reverse = "";
int length = str.length();
for( int i = length - 1 ; i >= 0 ; i-- ) {
reverse = reverse + str.charAt(i);
}
return reverse;
}
And in your main, you simply:
String reversed = myReverse(in.nextLine());
Note that the method is static because you're referring to it from a static manner (main method). If you don't want it to be static, you'll have to access it via an object.
Also note that it's a good practice to always have curly brackets for for loops, even if it contains a single line.
how do write the method that accepts String as an argument?
public static String reverse(String forward) {
char[] strChar = forward.toCharArray();
String reverse = "";
for( int i = strChar.length - 1 ; i >= 0 ; i-- )
reverse = reverse + strChar[i];
return reverse;
}
But for large string appending character with + operator can be inefficient. And reversing string with above approach will result in wrong for uni-code mismatches. As it reverse the code units but not character. There is actually a built-in support available to reverse a string using StringBuilder which works correctly:
public static String reverse(String forward) {
StringBuilder builder = new StringBuilder(forward);
String reverse = builder.reverse().toString();
return reverse;
}
Something like this:
public class StringUtils {
public static String reverse(String forward) {
String result = "";
// Put your code here
return result;
}
}
Using Java 9 you can implement something like this. This code works with both regular characters and surrogate pairs:
public static void printReverse(String str) {
// character code points
str.codePoints()
// character as string
.mapToObj(Character::toString)
// concatenate in reverse order
.reduce((a, b) -> b + a)
// output
.ifPresent(System.out::println);
}
public static void main(String[] args) {
// regular characters
printReverse("lorem ipsum");
// surrogate pairs
printReverse("\uD835\uDD43\uD835\uDD46R\uD835\uDD3C\uD835\uDD44" +
" \uD835\uDD40P\uD835\uDD4A\uD835\uDD4C\uD835\uDD44");
}
Output:
muspi merol
š•„š•Œš•ŠPš•€ š•„š”¼Rš•†š•ƒ
See also: Is there any other way to remove all whitespaces in a string?
Try this:
private static String reverseString(String str) {
String revString = "";
for (int i = str.length() - 1; i >= 0; i--) {
revString = revString + str.charAt(i);
}
return revString;
}
package dowhile;
public class Dowhile {
public static void main(String[] args) {
// TODO code application logic here
String message = "i love java programming";
int msglength = message.length();
int index = msglength - 1;
while (index >= 0) {
System.out.print(message.charAt(index));
index--;
}
}
}
Output:
gnimmargorp avaj evol i
private static void printReverse(String org) {
StringBuffer buffer = new StringBuffer(org);
String reversedStr = buffer.reverse().toString();
System.out.println("The reverse of the string \""
+ str + "\" is \"" + reversedStr + "\".");
}
in the main call the function
printReverse(original);

How to remove single character from a String by index

For accessing individual characters of a String in Java, we have String.charAt(2). Is there any inbuilt function to remove an individual character of a String in java?
Something like this:
if(String.charAt(1) == String.charAt(2){
//I want to remove the individual character at index 2.
}
You can also use the StringBuilder class which is mutable.
StringBuilder sb = new StringBuilder(inputString);
It has the method deleteCharAt(), along with many other mutator methods.
Just delete the characters that you need to delete and then get the result as follows:
String resultString = sb.toString();
This avoids creation of unnecessary string objects.
You can use Java String method called replace, which will replace all characters matching the first parameter with the second parameter:
String a = "Cool";
a = a.replace("o","");
One possibility:
String result = str.substring(0, index) + str.substring(index+1);
Note that the result is a new String (as well as two intermediate String objects), because Strings in Java are immutable.
No, because Strings in Java are immutable. You'll have to create a new string removing the character you don't want.
For replacing a single char c at index position idx in string str, do something like this, and remember that a new string will be created:
String newstr = str.substring(0, idx) + str.substring(idx + 1);
String str = "M1y java8 Progr5am";
deleteCharAt()
StringBuilder build = new StringBuilder(str);
System.out.println("Pre Builder : " + build);
build.deleteCharAt(1); // Shift the positions front.
build.deleteCharAt(8-1);
build.deleteCharAt(15-2);
System.out.println("Post Builder : " + build);
replace()
StringBuffer buffer = new StringBuffer(str);
buffer.replace(1, 2, ""); // Shift the positions front.
buffer.replace(7, 8, "");
buffer.replace(13, 14, "");
System.out.println("Buffer : "+buffer);
char[]
char[] c = str.toCharArray();
String new_Str = "";
for (int i = 0; i < c.length; i++) {
if (!(i == 1 || i == 8 || i == 15))
new_Str += c[i];
}
System.out.println("Char Array : "+new_Str);
To modify Strings, read about StringBuilder because it is mutable except for immutable String. Different operations can be found here https://docs.oracle.com/javase/tutorial/java/data/buffers.html. The code snippet below creates a StringBuilder and then append the given String and then delete the first character from the String and then convert it back from StringBuilder to a String.
StringBuilder sb = new StringBuilder();
sb.append(str);
sb.deleteCharAt(0);
str = sb.toString();
Consider the following code:
public String removeChar(String str, Integer n) {
String front = str.substring(0, n);
String back = str.substring(n+1, str.length());
return front + back;
}
You may also use the (huge) regexp machine.
inputString = inputString.replaceFirst("(?s)(.{2}).(.*)", "$1$2");
"(?s)" - tells regexp to handle newlines like normal characters (just in case).
"(.{2})" - group $1 collecting exactly 2 characters
"." - any character at index 2 (to be squeezed out).
"(.*)" - group $2 which collects the rest of the inputString.
"$1$2" - putting group $1 and group $2 together.
If you want to remove a char from a String str at a specific int index:
public static String removeCharAt(String str, int index) {
// The part of the String before the index:
String str1 = str.substring(0,index);
// The part of the String after the index:
String str2 = str.substring(index+1,str.length());
// These two parts together gives the String without the specified index
return str1+str2;
}
By the using replace method we can change single character of string.
string= string.replace("*", "");
Use replaceFirst function of String class. There are so many variants of replace function that you can use.
If you need some logical control over character removal, use this
String string = "sdsdsd";
char[] arr = string.toCharArray();
// Run loop or whatever you need
String ss = new String(arr);
If you don't need any such control, you can use what Oscar orBhesh mentioned. They are spot on.
Easiest way to remove a char from string
String str="welcome";
str=str.replaceFirst(String.valueOf(str.charAt(2)),"");//'l' will replace with ""
System.out.println(str);//output: wecome
public class RemoveCharFromString {
public static void main(String[] args) {
String output = remove("Hello", 'l');
System.out.println(output);
}
private static String remove(String input, char c) {
if (input == null || input.length() <= 1)
return input;
char[] inputArray = input.toCharArray();
char[] outputArray = new char[inputArray.length];
int outputArrayIndex = 0;
for (int i = 0; i < inputArray.length; i++) {
char p = inputArray[i];
if (p != c) {
outputArray[outputArrayIndex] = p;
outputArrayIndex++;
}
}
return new String(outputArray, 0, outputArrayIndex);
}
}
In most use-cases using StringBuilder or substring is a good approach (as already answered). However, for performance critical code, this might be a good alternative.
/**
* Delete a single character from index position 'start' from the 'target' String.
*
* ````
* deleteAt("ABC", 0) -> "BC"
* deleteAt("ABC", 1) -> "B"
* deleteAt("ABC", 2) -> "C"
* ````
*/
public static String deleteAt(final String target, final int start) {
return deleteAt(target, start, start + 1);
}
/**
* Delete the characters from index position 'start' to 'end' from the 'target' String.
*
* ````
* deleteAt("ABC", 0, 1) -> "BC"
* deleteAt("ABC", 0, 2) -> "C"
* deleteAt("ABC", 1, 3) -> "A"
* ````
*/
public static String deleteAt(final String target, final int start, int end) {
final int targetLen = target.length();
if (start < 0) {
throw new IllegalArgumentException("start=" + start);
}
if (end > targetLen || end < start) {
throw new IllegalArgumentException("end=" + end);
}
if (start == 0) {
return end == targetLen ? "" : target.substring(end);
} else if (end == targetLen) {
return target.substring(0, start);
}
final char[] buffer = new char[targetLen - end + start];
target.getChars(0, start, buffer, 0);
target.getChars(end, targetLen, buffer, start);
return new String(buffer);
}
*You can delete string value use the StringBuilder and deletecharAt.
String s1 = "aabc";
StringBuilder sb = new StringBuilder(s1);
for(int i=0;i<sb.length();i++)
{
char temp = sb.charAt(0);
if(sb.indexOf(temp+"")!=1)
{
sb.deleteCharAt(sb.indexOf(temp+""));
}
}
To Remove a Single character from The Given String please find my method hope it will be usefull. i have used str.replaceAll to remove the string but their are many ways to remove a character from a given string but i prefer replaceall method.
Code For Remove Char:
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
public class Removecharacter
{
public static void main(String[] args)
{
String result = removeChar("Java", 'a');
String result1 = removeChar("Edition", 'i');
System.out.println(result + " " + result1);
}
public static String removeChar(String str, char c) {
if (str == null)
{
return null;
}
else
{
return str.replaceAll(Character.toString(c), "");
}
}
}
Console image :
please find The Attached image of console,
Thanks For Asking. :)
public static String removechar(String fromString, Character character) {
int indexOf = fromString.indexOf(character);
if(indexOf==-1)
return fromString;
String front = fromString.substring(0, indexOf);
String back = fromString.substring(indexOf+1, fromString.length());
return front+back;
}
BufferedReader input=new BufferedReader(new InputStreamReader(System.in));
String line1=input.readLine();
String line2=input.readLine();
char[] a=line2.toCharArray();
char[] b=line1.toCharArray();
loop: for(int t=0;t<a.length;t++) {
char a1=a[t];
for(int t1=0;t1<b.length;t1++) {
char b1=b[t1];
if(a1==b1) {
StringBuilder sb = new StringBuilder(line1);
sb.deleteCharAt(t1);
line1=sb.toString();
b=line1.toCharArray();
list.add(a1);
continue loop;
}
}
When I have these kinds of questions I always ask: "what would the Java Gurus do?" :)
And I'd answer that, in this case, by looking at the implementation of String.trim().
Here's an extrapolation of that implementation that allows for more trim characters to be used.
However, note that original trim actually removes all chars that are <= ' ', so you may have to combine this with the original to get the desired result.
String trim(String string, String toTrim) {
// input checks removed
if (toTrim.length() == 0)
return string;
final char[] trimChars = toTrim.toCharArray();
Arrays.sort(trimChars);
int start = 0;
int end = string.length();
while (start < end &&
Arrays.binarySearch(trimChars, string.charAt(start)) >= 0)
start++;
while (start < end &&
Arrays.binarySearch(trimChars, string.charAt(end - 1)) >= 0)
end--;
return string.substring(start, end);
}
public String missingChar(String str, int n) {
String front = str.substring(0, n);
// Start this substring at n+1 to omit the char.
// Can also be shortened to just str.substring(n+1)
// which goes through the end of the string.
String back = str.substring(n+1, str.length());
return front + back;
}
I just implemented this utility class that removes a char or a group of chars from a String. I think it's fast because doesn't use Regexp. I hope that it helps someone!
package your.package.name;
/**
* Utility class that removes chars from a String.
*
*/
public class RemoveChars {
public static String remove(String string, String remove) {
return new String(remove(string.toCharArray(), remove.toCharArray()));
}
public static char[] remove(final char[] chars, char[] remove) {
int count = 0;
char[] buffer = new char[chars.length];
for (int i = 0; i < chars.length; i++) {
boolean include = true;
for (int j = 0; j < remove.length; j++) {
if ((chars[i] == remove[j])) {
include = false;
break;
}
}
if (include) {
buffer[count++] = chars[i];
}
}
char[] output = new char[count];
System.arraycopy(buffer, 0, output, 0, count);
return output;
}
/**
* For tests!
*/
public static void main(String[] args) {
String string = "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG";
String remove = "AEIOU";
System.out.println();
System.out.println("Remove AEIOU: " + string);
System.out.println("Result: " + RemoveChars.remove(string, remove));
}
}
This is the output:
Remove AEIOU: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG
Result: TH QCK BRWN FX JMPS VR TH LZY DG
For example if you want to calculate how many a's are there in the String, you can do it like this:
if (string.contains("a"))
{
numberOf_a++;
string = string.replaceFirst("a", "");
}

Take (n) characters from a string

I have a string in java, of uncertain length, and I need to take the first 3 and last 3 characters and put them into new strings. Is there a simple way to do this?
Funny, all solutions are buggy (update: except the one with the regex) and may result in StringIndexOutOfBoundsException when the input string's length is less then 3 (the question explicitly says the length is uncertain). Assuming that str is not null, the proper way would be:
String first = str.substring(0, Math.min(str.length(), 3));
String second = str.substring(Math.max(0, str.length() - 3), str.length());
You could use the substring method:
String text = "Hello world!";
String newText = text.substring(0, 3) + text.substring(text.length-3);
This will take "Hello world!" and create a new string which is "Helld!".
If you are looking for a method that you can use:
String trimThreeCharacters(text){
return text.substring(0,3) + text.substring(text.length-3);
}
str.substring(0, 3) + str.substring(str.length - 3)
EDIT:
This code is not safe. I leave it for you to check whether string is not too short.
You can also use regular expressions:
Pattern p = Pattern.compile("^(.{3}).*(.{3})$");
Matcher m = p.matcher(str);
if (m.find()) {
String s1 = m.group(1);
String s2 = m.group(2);
}
Refer to documentation
public class Substring {
public static void main(String[] args) {
String input = "very long string, with random content";
System.out.println(input.substring(0, 3));
int length = input.length();
System.out.println(input.substring(length - 3));
}
}
Result
ver
ent
Another way of doing this
public class MyString
{
private String value;
public MyString(String p_value)
{
value = p_value;
}
public String getFirstThree()
{
return value.substring(0, 3);
}
public String getLastThree()
{
return value.substring(value.length() - 3);
}
public String getNewString()
{
return getFirstThree() + getLastThree();
}
public static void main(String[] args)
{
MyString example = new MyString("hello world");
String newString = example.getNewString();
System.out.println(newString);
}
}
new_string = old_string.substring(0,3) +
old_string.substring(old_string.lenght() - 3)
As milan already said, substring is the way to go here. You can see some examples of use here.
String FullName = "Cande Nauer";
String FirstNameChars = "";
FirstNameChars = FullName.substring( 0, 3 );
In this example, FirstNameChars will be "Can". To get the last three characters you will have to obtain the length og the string first.

Categories

Resources