I have a string which contains 80+ characters and I want to divide it into two substrings. The first one to contain the first 80 characters and the other one the next characters.
I was able to obtain the first String.
public static void SetStrings(String stringName) {
int numOfChars = stringName.length();
String firstString = stringName.substring(0, 80);
int maxChars = 80;
if (numOfChars > maxChars) {
stringName = firstString;
} else {
stringName = stringName;
}
}
Use this:
String secondString = stringName.substring(80);
You should also look at the Javadoc for String.substring(int).
Related
public class Test {
public static void main(String[] args) {
String str = "My CID is #encode2#123456789#encode2# I am from India";
String[] tokens = str.split("#encode2#");
for (int i = 0; i < tokens.length; i++) {
// prints the tokens
System.out.println(tokens[i]);
}
}
}
Output will be
My CID is
123456789
I am from India
But I want only 123456789 from this whole String and I want to use that 123456789 number for encryption.
I also use if(!"#encode2#".equals(text)) condition but still not getting output.
How to write condition like need strat from #encode2# right part and end before #encode2#.
Use String's indexOf and lastIndexOf methods to find the index where the two #encode2# substrings start. Then, use substring to get the string between those two indices.
String str = "My CID is #encode2#123456789#encode2# I am from India";
String substring = "#encode2#";
int firstIdx = str.indexOf(substring);
int secondIdx = str.lastIndexOf(substring);
System.out.println(str.substring(firstIdx + substring.length(), secondIdx)); //123456789
public String getToken() {
String str = "My CID is #encode2#123456789#encode2# I am from India";
int start = str.indexOf("#encode2#") + "#encode2#".length();
int end = str.lastIndexOf("#encode2#");
return str.substring(start, end);
}
Note: This method only works if you have "#encode2#" twice in your String value. If you there are multiple instances of the Token you need, this doesn't work.
In my plugin for Spigot, a player enters a command such as /logging chat clear 1d. The argument number 2 (3rd arg) which is 1d needs to be parsed for date (e.g. 1d = 1 day, 15m = 15 minutes). I've figured out the parsing part, but when I try to parse more than one number (1 vs 11) my parsing doesn't work because I split based on characters, not based on if its an integer or string. I do String[] part = arg3.split(""); then take the first character as the number and second as the string.
How can I do this but split so that I can have multiple numbers? (regex?)
private void myMethod() {
String integers = "";
String characters = "";
String splitArgument = ""; //this is the 1d or 11d part
for(int x = 0; x < splitArgument.length(); x++) {
Char currentChar = splitArgument.charAt(x);
if(Character.isDigit(currentChar)) {
integers += currentChar;
}else {
characters += currentChar;
}
}
}
Where myMethod just represents the area of the code you are analyzing the input in. You can create a method (as isInteger()) that takes the characters from the String you are checking and determines whether they are Integers/String and re-concatenate Strings for them. For the integer part you could then do:
int myInteger = Integer.parseInt(integers);
Use a Regex.
import java.util.regex.*;
Pattern pattern = Pattern.compile("(\\d+)([a-zA-Z]+)");
Matcher matcher = pattern.matcher(text);
if(matcher.find()){
String number = matcher.group(1);
String letters = matcher.group(2);
}
You can simply do this on the condition that the date argument is always a single character at the end of the String.
public static String[] splitDate(String date)
{
int length = date.length();
String[] results = {date.substring(0, length - 1), date.substring(length - 1)};
return results;
}
Input of 110w will return an array of {110, w}.
This method just uses substring based on the length of String and separates the number from the final character.
I have a word on which I need to replace a certain character with an asterisk, but I need to get all the replaced variations from this word. For eg. I want to replace character 'e' with an asterisk in:
String word = telephone;
but to get this list as a result:
List of words = [t*lephone, tel*phone, telephon*, t*l*phone, t*lephon*, tel*phon*, t*l*phon*];
Is there a quick way to do this in Java?
The following code will do that in a recursive way:
public static Set<String> getPermutations(final String string, final char c) {
final Set<String> permutations = new HashSet<>();
final int indexofChar = string.indexOf(c);
if (indexofChar <= 0) {
permutations.add(string);
} else {
final String firstPart = string.substring(0, indexofChar + 1);
final String firstPartReplaced = firstPart.replace(c, '*');
final String lastPart = string.substring(indexofChar + 1, string.length());
for (final String lastPartPerm : getPermutations(lastPart, c)) {
permutations.add(firstPart + lastPartPerm);
permutations.add(firstPartReplaced + lastPartPerm);
}
}
return permutations;
}
It adds the original String to the output, so:
public static void main(String[] args) {
String word = "telephone";
System.out.println(getPermutations(word, 'e'));
}
Outputs:
[telephone, t*lephone, tel*phone, t*l*phone, telephon*, t*lephon*, tel*phon*, t*l*phon*]
But you can always call remove on the returned Set with the original word.
I am working on a project and I dont know how to properly parse some input for example a1 = ("hello" + "World"). a1 is a cell that I made and i am trying to at the end put helloworld into that cell. This is one of my classes that I use parse input. When I use numbers it works fine but not with Strings. Im just trying to be able to parse an input like ("hi" + "man") to himan. I just want to be able to parse out the spaces and the plus sign and make himan into a single string.
import java.util.Scanner;
public class ParseInput {
private static String inputs;
static int col;
private static int row;
private static String operation;
private static Value field;
public static void parseInput(String input){
//splits the input at each regular expression match. \w is used for letters and \d && \D for integers
inputs = input;
Scanner tokens = new Scanner(inputs);
String[] strings = input.split("=");
String s1 = strings[0].trim(); // a1
String s2 = strings[1].trim(); // "Hello" + "World"
strings = s2.split("\\+");
String s3 = strings[0].trim().replaceAll("^\"", "").replaceAll("\"$", ""); // Hello
String s4 = strings[1].trim().replaceAll("^\"", "").replaceAll("\"$", ""); // World
String field = s3 + s4;
String colString = s1.replaceAll("[\\d]", ""); // a
String rowString = s1.replaceAll("[\\D]", ""); // 1
int col = colString.charAt(0) - 'a'; // 0
int row = Integer.parseInt(rowString);
TextValue fieldvalue = new TextValue(field);
Spreadsheet.changeCell(row, col, fieldvalue);
String none0 = tokens.next();
#SuppressWarnings("unused")
String none1 = tokens.next();
operation = tokens.nextLine().substring(1);
String[] holder = new String[2];
String regex = "(?<=[\\w&&\\D])(?=\\d)";
holder = none0.split(regex);
row = Integer.parseInt(holder[1]);
col = 0;
int counter = -1;
char temp = holder[0].charAt(0);
char check = 'a';
while(check <= temp){
if(check == temp){
col = counter +1;
}
counter++;
check = (char) (check + 1);
}
System.out.println(col);
System.out.println(row);
System.out.println(operation);
setField(Value.parseValue(operation));
Spreadsheet.changeCell(row, col, fieldvalue);
}
public static Value getField() {
return field;
}
public static void setField(Value field) {
ParseInput.field = field;
}
}
If you're trying to remove spaces, it's a one-liner...
input = input.replaceAll("[\\s+\"]", "");
The other way to do this would be to simply remove all "non word" chars (defined as 0-9, a-z, A-Z and the underscore):
input = input.replaceAll("\\W", "");
Use a StringBuilder. String is immutable in Java, which means you will be creating a new instance every time you want to combine two strings. Use the append() method (it accepts just about anything) to add something onto the end.
StringBuilder input = "";
input.append("hel").append("lo");
Here is the documentation for it. Take a look.
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");