Java - Removing First Character of a String

Remove first character of string in O(1)

There is no way to get the characters of a String without first copying them, which takes O(n) time as it has to transverse the entire string to copy it... unless you use reflection.

Now you talk about replacing the first letter in the string and replacing the first letter of each word in the string interchangeably. If you want to replace the first letter of each word, you're going to have to transverse the entire string which is O(n) time - there is just no other way.

If you only want to replace the first letter, you can use reflection, but I wouldn't suggest you actually do this, rather just use .substring(String).

The method you're looking for:

/**
* Replaces the first letter in a {@code String} in O(1) time.
*
* This uses reflection to change the values and will modify the
* {@code String}s values.
*
* @param str the {@code String} to modify.
* @param letter the new first letter of the {@code String}.
* @return {@code str}
*/
public static String replaceFirstLetter(String str, char letter) {
if (str == null) {
throw new NullPointerException("str cannot be null");
}

if (str.length() == 0) {
throw new IllegalArgumentException("String cannot be empty");
}

try {
Field value
= str.getClass().getDeclaredField("value");

value.setAccessible(true);

Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(value, value.getModifiers() & ~Modifier.FINAL);

char[] values = (char[]) value.get(str);
values[0] = letter;
value.set(str, values);

} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException ex) {
ex.printStackTrace();
//This should never happen
}

return str;
}

Note that this method will modify the String you pass in, so this breaks the immutable rule of the String class and should not be used in production code. Also, it will probably be quicker to just transverse the string than it will be to use this method.

public static void main(String[] args) {
String s = "Hello";
replaceFirstLetter(s, 'Y');
System.out.println(s);

System.out.println(replaceFirstLetter("Hello", 'G'));
}

This demonstrates it quite nicely.

How to remove the first and last character of a string?

You need to find the index of [ and ] then substring. (Here [ is always at start and ] is at end):

String loginToken = "[wdsd34svdf]";
System.out.println( loginToken.substring( 1, loginToken.length() - 1 ) );

Removing the first 3 characters from a string

Just use substring: "apple".substring(3); will return le

Delete Last and First Char in a String

String s = "Hello World!";
s = s.substring(1, s.length() - 1); // --> "ello World"

How to remove the first character of every string in an array in java

Might not be full answer but first of all you are defining one element array. I would recommend jshell (with jdk9+) which is java REPL to play with java code and see how it reacts.

jshell> String[] deck = {"apple, banana, cat"}
deck ==> String[1] { "apple, banana, cat" }

You instead want to separate elements, and see the size is 3.

jshell> String[] deck = {"apple", "banana", "cat"}
deck ==> String[3] {"apple", "banana", "cat"}

Then you should be able to .substring(1) to get the card point ignoring the first char and convert it to integer later.

Example:

public static void main(String[] args) {
String[] deck = {
"DA",
"D2",
"D3",
"D4",
"D5",
"D6",
"D7",
"D8",
"D9",
"D10",
"DJ",
"DQ",
"DK",
"SA",
"S2",
"S3",
"S4",
"S5",
"S6",
"S7",
"S8",
"S9",
"S10",
"SJ",
"SQ",
"SK",
"HA",
"H2",
"H3",
"H4",
"H5",
"H6",
"H7",
"H8",
"H9",
"H10",
"HJ",
"HQ",
"HK",
"CA",
"C2",
"C3",
"C4",
"C5",
"C6",
"C7",
"C8",
"C9",
"C10",
"CJ",
"CQ",
"CK"
};

String[] points = new String[deck.length];

for (int i = 0; i < deck.length; i++) {
points[i] = deck[i].substring(1);
}

System.out.println(Arrays.toString(points));
}

output:

[A, 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K, A, 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K, A, 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K, A, 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K]

How to remove single character from a String by index

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.

How to remove all characters before a specific character in Java?

You can use .substring():

String s = "the text=text";
String s1 = s.substring(s.indexOf("=") + 1);
s1.trim();

then s1 contains everything after = in the original string.

s1.trim()

.trim() removes spaces before the first character (which isn't a whitespace, such as letters, numbers etc.) of a string (leading spaces) and also removes spaces after the last character (trailing spaces).



Related Topics



Leave a reply



Submit