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.
Related
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);
}
I need to replace first and middle char in string but without builder and etc, just with replace but idk how to make it.
String char = JOptionPane.showInputDialog(null, "Input string with more than 3 char");
if (char.length() < 3) {
JOptionPane.showMessageDialog(null, "Wrong input");
I just made this code and that is it, idk how to continue.
Example: input - pniut
I tried with smth like char.length / 2 but cant.
You can convert your string to a character array, and then swap the characters at 0 and middle position. Then convert the array back to String. e.g. I hard coded 2 here but like you mentioned in comments, you will need to figure out the character at the middle position.
String str = "input";
int mid = -1;
if(str.length() % 2 == 0) {
str.length() / 2 - 1
} else {
str.length() / 2;
}
char[] arr = str.toCharArray();
char temp = '0';
temp = arr[0];
arr[0] = arr[mid];
arr[mid] = temp;
String.valueOf(arr);
The value of the middle character, you will need to find out, like you said in the comments.
Since String objects are immutable, converting the original String to a char[] via toCharArray(), replace the characters, then making a new String from char[] via the String(char[]) constructor would work as shown below:
char[] c = character.toCharArray();
// Change characters at desired indicies
c[0] = 'p'; // first character
c[character.length()/2] = 'i'; // approximate middle character
String newString = new String(c);
System.out.println(newString); // "pniut"
Simple answer: not possible (for generic cases).
Meaning: all variants of String.replace() work by replacing one thing with another. There is no notion of using an index anywhere. So you can't say "replace index 1 with A" and "index 3 with B".
The simply solution is to push the string into a char[], to then swap/replace individual characters via index.
I'm betting the goal of the lesson is to learn how to use the API. So would start here Java API. Go to java.lang.String.
I would focus on the .toCharArray() method and the constructor that takes a char[] as an argument. You need to do this because a String is immutable, and cannot be changed. A char[], however can be altered, allowing you to modify the first and middle slots. You can then take your altered array and convert it back into a String.
How do I split string between From text.charAt(9) till next space occurs in java?
jhb 9jb 38888 hjbhjb7868hgvhv
I need to extact 38888
you can use
String text = "jhb 9jb 38888 hjbhjb7868hgvhv";
String subStrings[]=text.split(" ");
System.out.println(subString[2]);
You can use substring method twice.
First, get substring from 9th character (till the end of the String)
Get another substring from 0 to index of the first whitespace, for the String retrieved in above step
String s = "jhb 9jb 38888 hjbhjb7868hgvhv";
String subString = s.substring(8);
System.out.println(subString.substring(0, subString.indexOf(" ")));
How about this
String s = "jhb 9jb 38888 hjbhjb7868hgvhv";
System.out.println(s.substring(8, s.length()).split(" ")[0]);
Just takes a substring, and then splits it.
Find the first occurrence of the ninth character:
// If you actually mean the ninth character, pos = 9.
int pos = text.indexOf(text.charAt(9));
Find the next space:
int nextSpace = text.indexOf(' ', pos);
Then take the substring between them:
String part = text.substring(pos, nextSpace);
Note that you may need to handle the case where no space follows, so nextSpace == -1.
given this string http://verylongurlverylonngurl/image.jpg & I wanna cut all the part before the last "/". For example, I wanna remove the part http://verylongurlverylonngurl/ of the string above. The result will be "image.jpg".
I have to cut the String "Label" & the code to cut that String must be inside the super() keyword & super keyword must be the first statement in the constructor. Loook at this code:
private class TextShortenedCheckBox extends CheckBox{
private String originalText;
public TextShortenedCheckBox(String label, int visibleLength){
super(label.substring(label.length()-9,label.length()-1));
originalText=label;
}
#Override
public String getText(){
return originalText;
}
}
Look at the code: label.substring(label.length()-9,label.length()-1) this code give the result but not be able to apply for other variable string.
So, how to cut a part of a String by just 1 line of code, so that I can put that code inside super(). Maybe we have to use Regex or something?
What about
str = str.substring(str.lastIndexOf("/") + 1);
Try this:
String str ="http://verylongurlverylonngurl/image.jpg";
str = str.substring(str.lastIndexOf("/")+1);
System.out.println(str);
Output:
image.jpg
You can use lastIndexOf('/')
Returns the index within this string of the last occurrence of the specified character. For values of ch in the range from 0 to 0xFFFF (inclusive), the index (in Unicode code units) returned is the largest value k such that: this.charAt(k) == ch is true. For other values of ch, it is the largest value k such that: this.codePointAt(k) == ch is true. In either case, if no such character occurs in this string, then -1 is returned. The String is searched backwards starting at the last character.
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("")
}
}