How do I delete anything after 6 characters in a String? - java

So I have a bunch of strings that only need to contain the first 6 characters. Is there an algorithm than can take a string and remove anything that comes after the 6th character?

Just use String's substring() method
String value = "abcdefghijkl";
String newValue = value.substring(0, 6); // "abcdef"
substring reference

str = str.substring(0, 6);
That will cut the string to the 6th letter.

use substring method:
public String removeExtra(String s)
{
return s.substring(0,6);
}

Related

How to fix ReplaceAll function in java code

i am trying to replace all occurrences of the first character in a string with another using the replace all function. However, no change occurs when i run the function. I tried to target the first character of the original string and then carry the out the replacement but no luck. Below is a snippet of my code.
public static String charChangeAt(String str, String str2) {
//str = x.xy
//str2 = d.w
String res = str.replaceAll(Character.toString(str.charAt(0)), str2);
return res ;
}
Your code replaces all characters that match the first character. If your string is abcda and you run your function, it will replace all occurences of a with whatever you put. Including the last one.
To achieve your goal you should probably not use replaceAll.
You could use StringBuilder.
StringBuilder builder = new StringBuilder(str);
myName.setCharAt(0, str2.charAt(0));
In case you want to replace all occurrences of the first character in a string with another, you can use replace instead of replaceAll. Below is the code snippet.
String str = "x.xy";
String str2 = "d.w";
String res = str.replace(Character.toString(str.charAt(0)), str2);
return res; // will output d.w.d.wy
Your function works fine but you probably are using it the wrong way.
For these strings:
String str = "abaca";
String str2 = "x";
if you do:
charChangeAt(str, str2);
this will not affect str.
You must assign the value returned by your function to str:
str = charChangeAt(str, str2);
This will change the value of str to:
"xbxcx"

Remove trailing substring from String in Java

I am looking to remove parts of a string if it ends in a certain string.
An example would be to take this string: "am.sunrise.ios#2x.png"
And remove the #2x.png so it looks like: "am.sunrise.ios"
How would I go about checking to see if the end of a string contains "#2x.png" and remove it?
You could check the lastIndexOf, and if it exists in the string, use substring to remove it:
String str = "am.sunrise.ios#2x.png";
String search = "#2x.png";
int index = str.lastIndexOf(search);
if (index > 0) {
str = str.substring(0, index);
}
Assuming you have a string initialized as String file = "am.sunrise.ios#2x.png";.
if(file.endsWith("#2x.png"))
file = file.substring(0, file.lastIndexOf("#2x.png"));
The endsWith(String) method returns a boolean determining if the string has a certain suffix. Depending on that you can replace the string with a substring of itself starting with the first character and ending before the index of the character that you are trying to remove.
private static String removeSuffixIfExists(String key, String suffix) {
return key.endswith(suffix)
? key.substring(0, key.length() - suffix.length())
: key;
}
}
String suffix = "#2x.png";
String key = "am.sunrise.ios#2x.png";
String output = removeSuffixIfExists(key, suffix);
public static void main(String [] args){
String word = "am.sunrise.ios#2x.png";
word = word.replace("#2x.png", "");
System.out.println(word);
}
If you want to generally remove entire content of string from # till end you can use
yourString = yourString.replaceAll("#.*","");
where #.* is regex (regular expression) representing substring starting with # and having any character after it (represented by .) zero or more times (represented by *).
In case there will be no #xxx part your string will be unchanged.
If you want to change only this particular substring #2x.png (and not substirng like #3x.png) while making sure that it is placed at end of your string you can use
yourString = yourString.replaceAll("#2x\\.png$","");
where
$ represents end of string
\\. represents . literal (we need to escape it since like shown earlier . is metacharacter representing any character)
Since I was trying to do this on an ArrayList of items similarly styled I ended up using the following code:
for (int image = 0; image < IBImages.size(); image++) {
IBImages.set(image, IBImages.get(image).split("~")[0].split("#")[0].split(".png")[0]);
}
If I have a list of images with the names
[am.sunrise.ios.png, am.sunrise.ios#2x.png, am.sunrise.ios#3x.png, am.sunrise.ios~ipad.png, am.sunrise.ios~ipad#2x.png]
This allows me to split the string into 2 parts.
For example, "am.sunrise.ios~ipad.png" will be split into "am.sunrise.ios" and "~ipad.png" if I split on "~". I can just get the first part back by referencing [0]. Therefore I get what I'm looking for in one line of code.
Note that image is "am.sunrise.ios~ipad.png"
You could use String.split():
public static void main(String [] args){
String word = "am.sunrise.ios#2x.png";
String[] parts = word.split("#");
if (parts.length == 2) {
System.out.println("looks like user#host...");
System.out.println("User: " + parts[0]);
System.out.println("Host: " + parts[1]);
}
}
Then you haven an array of Strings, where the first element contains the part before "#" and the second element the part after the "#".
Combining the answers 1 and 2:
String str = "am.sunrise.ios#2x.png";
String search = "#2x.png";
if (str.endsWith(search)) {
str = str.substring(0, str.lastIndexOf(search));
}

Remove all spaces and punctuation (anything not a letter) from a string?

In Java, how can I take a string as a parameter, and then remove all punctuation and spaces and then convert the rest of the letters to uppercase?
Example 1:
Input: How's your day going?
Output: HOWSYOURDAYGOING
Example 2:
Input: What's your name again?
Output: WHATSYOURNAMEAGAIN
This should do the trick
String mystr= "How's your day going?";
mystr = mystr.replaceAll("[^A-Za-z]+", "").toUpperCase();
System.out.println(mystr);
Output:
HOWSYOURDAYGOING
The regex [^A-Za-z]+ means one or more characters that do not match anything in the range A-Za-z, and we replace them with the empty string.
String yourString = "How's your day going";
yourString=yourString.replaceAll("\\s+",""); //remove white space
yourString=yourString.replaceAll("[^a-zA-Z ]", ""); //removes all punctuation
yourString=yourString.toUpperCase(); //convert to Upper case
I did it with
inputText = inputText.replaceAll("\\s|[^a-zA-Z0-9]","");
inputText.toUpper(); //and later uppercase the complete string
Though #italhourne 's answer is correct but you can just reduce it in single step by just removing the spaces as well as keeping all the characters from a-zA-Z and 0-9, in a single statement by adding "or".
Just a help for those who need it!!
public static String repl1(String n){
n = n.replaceAll("\\p{Punct}|\\s","");
return n;
}
Well, I did it the long way, take a look if you want. I used the ACII code values (this is my main method, transform it to a function on your own).
String str="How's your day going?";
char c=0;
for(int i=0;i<str.length();i++){
c=str.charAt(i);
if(c<65||(c>90&&c<97)||(c>122)){
str=str.replace(str.substring(i,i+1) , "");
}
}
str=str.toUpperCase();
System.out.println(str);

Is it possible to get only the first character of a String?

I have a for loop in Java.
for (Legform ld : data)
{
System.out.println(ld.getSymbol());
}
The output of the above for loop is
Pad
CaD
CaD
CaD
Now my question is it possible to get only the first characer of the string instead of the whole thing Pad or CaD
For example if it's Pad I need only the first letter, that is P
For example if it's CaD I need only the first letter, that is C
Is this possible?
Use ld.charAt(0). It will return the first char of the String.
With ld.substring(0, 1), you can get the first character as String.
String has a charAt method that returns the character at the specified position. Like arrays and Lists, String is 0-indexed, i.e. the first character is at index 0 and the last character is at index length() - 1.
So, assuming getSymbol() returns a String, to print the first character, you could do:
System.out.println(ld.getSymbol().charAt(0)); // char at index 0
The string has a substring method that returns the string at the specified position.
String name="123456789";
System.out.println(name.substring(0,1));
Here I am taking Mobile No From EditText It may start from +91 or 0 but i am getting actual 10 digits.
Hope this will help you.
String mob=edit_mobile.getText().toString();
if (mob.length() >= 10) {
if (mob.contains("+91")) {
mob= mob.substring(3, 13);
}
if (mob.substring(0, 1).contains("0")) {
mob= mob.substring(1, 11);
}
if (mob.contains("+")) {
mob= mob.replace("+", "");
}
mob= mob.substring(0, 10);
Log.i("mob", mob);
}
Answering for C++ 14,
Yes, you can get the first character of a string simply by the following code snippet.
string s = "Happynewyear";
cout << s[0];
if you want to store the first character in a separate string,
string s = "Happynewyear";
string c = "";
c.push_back(s[0]);
cout << c;
Java strings are simply an array of char. So, char c = s[0] where s is string.

Java - removing first character of a string

In Java, I have a String:
Jamaica
I would like to remove the first character of the string and then return amaica
How would I do this?
const str = "Jamaica".substring(1)
console.log(str)
Use the substring() function with an argument of 1 to get the substring from position 1 (after the first character) to the end of the string (leaving the second argument out defaults to the full length of the string).
public String removeFirstChar(String s){
return s.substring(1);
}
In Java, remove leading character only if it is a certain character
Use the Java ternary operator to quickly check if your character is there before removing it. This strips the leading character only if it exists, if passed a blank string, return blankstring.
String header = "";
header = header.startsWith("#") ? header.substring(1) : header;
System.out.println(header);
header = "foobar";
header = header.startsWith("#") ? header.substring(1) : header;
System.out.println(header);
header = "#moobar";
header = header.startsWith("#") ? header.substring(1) : header;
System.out.println(header);
Prints:
blankstring
foobar
moobar
Java, remove all the instances of a character anywhere in a string:
String a = "Cool";
a = a.replace("o","");
//variable 'a' contains the string "Cl"
Java, remove the first instance of a character anywhere in a string:
String b = "Cool";
b = b.replaceFirst("o","");
//variable 'b' contains the string "Col"
Use substring() and give the number of characters that you want to trim from front.
String value = "Jamaica";
value = value.substring(1);
Answer: "amaica"
You can use the substring method of the String class that takes only the beginning index and returns the substring that begins with the character at the specified index and extending to the end of the string.
String str = "Jamaica";
str = str.substring(1);
substring() method returns a new String that contains a subsequence of characters currently contained in this sequence.
The substring begins at the specified start and extends to the character at index end - 1.
It has two forms. The first is
String substring(int FirstIndex)
Here, FirstIndex specifies the index at which the substring will
begin. This form returns a copy of the substring that begins at
FirstIndex and runs to the end of the invoking string.
String substring(int FirstIndex, int endIndex)
Here, FirstIndex specifies the beginning index, and endIndex specifies
the stopping point. The string returned contains all the characters
from the beginning index, up to, but not including, the ending index.
Example
String str = "Amiyo";
// prints substring from index 3
System.out.println("substring is = " + str.substring(3)); // Output 'yo'
you can do like this:
String str = "Jamaica";
str = str.substring(1, title.length());
return str;
or in general:
public String removeFirstChar(String str){
return str.substring(1, title.length());
}
public String removeFirst(String input)
{
return input.substring(1);
}
The key thing to understand in Java is that Strings are immutable -- you can't change them. So it makes no sense to speak of 'removing a character from a string'. Instead, you make a NEW string with just the characters you want. The other posts in this question give you a variety of ways of doing that, but its important to understand that these don't change the original string in any way. Any references you have to the old string will continue to refer to the old string (unless you change them to refer to a different string) and will not be affected by the newly created string.
This has a number of implications for performance. Each time you are 'modifying' a string, you are actually creating a new string with all the overhead implied (memory allocation and garbage collection). So if you want to make a series of modifications to a string and care only about the final result (the intermediate strings will be dead as soon as you 'modify' them), it may make more sense to use a StringBuilder or StringBuffer instead.
I came across a situation where I had to remove not only the first character (if it was a #, but the first set of characters.
String myString = ###Hello World could be the starting point, but I would only want to keep the Hello World. this could be done as following.
while (myString.charAt(0) == '#') { // Remove all the # chars in front of the real string
myString = myString.substring(1, myString.length());
}
For OP's case, replace while with if and it works aswell.
You can simply use substring().
String myString = "Jamaica"
String myStringWithoutJ = myString.substring(1)
The index in the method indicates from where we are getting the result string, in this case we are getting it after the first position because we dont want that "J" in "Jamaica".
Another solution, you can solve your problem using replaceAll with some regex ^.{1} (regex demo) for example :
String str = "Jamaica";
int nbr = 1;
str = str.replaceAll("^.{" + nbr + "}", "");//Output = amaica
My version of removing leading chars, one or multiple. For example, String str1 = "01234", when removing leading '0', result will be "1234". For a String str2 = "000123" result will be again "123". And for String str3 = "000" result will be empty string: "". Such functionality is often useful when converting numeric strings into numbers.The advantage of this solution compared with regex (replaceAll(...)) is that this one is much faster. This is important when processing large number of Strings.
public static String removeLeadingChar(String str, char ch) {
int idx = 0;
while ((idx < str.length()) && (str.charAt(idx) == ch))
idx++;
return str.substring(idx);
}
##KOTLIN
#Its working fine.
tv.doOnTextChanged { text: CharSequence?, start, count, after ->
val length = text.toString().length
if (length==1 && text!!.startsWith(" ")) {
tv?.setText("")
}
}

Categories

Resources