Remove spaces using substring - java

I have this:
private String remove_spaces(String s){
s = s.trim();
String updated = "";
for (int i = 0; i < s.length(); i++) {
String tester = s.substring(i, i + 1);
String space = " ";
boolean isSpace = tester.equals(space);
if (isSpace = false)
updated += tester;
}
return updated;
}
And it throws an StringIndexOutOfBounds, and I don't understand why. Why?

You've got index out of bounds error because you are trying to reach an index greater than the actual length of your array
String tester = s.substring(i,i + 1);
I suggest an if clause like this
private String remove_spaces(String s) {
s = s.trim();
String updated = "";
String tester = "";
for (int i = 0; i < s.length(); i++) {
if (i != s.length-1) {
tester = s.substring(i, i + 1);
}else{
tester = s.substring(i);
}
if (!tester.equals(" ")) {
updated += tester;
}
}
return updated;
}

You need == to do comparison while = is substitution operator.
if (isSpace == false)
Additionally, you can use !(=not) to shorten your code like below:
private String remove_spaces(String s) {
s = s.trim();
String updated = "";
for (int i = 0; i < s.length(); i++) {
String tester = s.substring(i, i + 1);
if (!tester.equals(" ")) {
updated += tester;
}
}
return updated;
}

The better way to remove spaces in your String in Java would be
str = str.replace(" ","");
But if you want something similar to your code, try the below one, I guess substring is not needed we can use charAt for that.
private static String remove_spaces(String s) {
s = s.trim();
StringBuilder updated = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
Character tester = s.charAt(i);
if (!tester.equals(' ')) {
updated.append(tester);
}
}
return updated.toString();
}

Related

How I return specific string from recursive function in java?

Input for method :
word = AbcDef
input = 3
w = AbcDef
The Following code showing the ouput :
fAbcDe
efAbcD
DefAbc
I want to return only DefAbc.
How can I do the coding for return keyword.
public static String match2(String word,int input,String w)
{
StringBuilder st = new StringBuilder();
StringBuilder st1 = new StringBuilder();
String str = "";
int count = 0;
st.append(word.charAt(i));
for(int j = 0;j < i;j++)
{
st.append(word.charAt(j));
}
if(input!=0)
{
str = st.toString();
System.out.println(str);
int input2 = input-1;
match2(str,input2,w);
}
return null;
}
Please try this one. Hope it might solve your problem using recursion-> tillValue should be->3 if you want to rotate for 3 characters
static String recurse(String word, int count, int tillValue) {
if (count == tillValue) {
return word;
}
String recurse = recurse(word, count + 1,tillValue);
word = swap(recurse);
return word;
}
private static String swap(String word) {
if (word.length() > 0) {
String c = word.substring(word.length() - 1);
String dc = c + word.substring(0, word.length() - 1);
System.out.println(dc);
return dc;
}
return "";
}

how to split a string by using charAt and string.length()

only allow charAt method and length method . Thank you so much!
void runApp() {
String str = "345, 688"; //->"345" "688"
String value = strCut(str);
}
String strCut(String str) {
int result = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(3) == ',') {
what should i write here ? ?
}
Your code needs some refactoring, try this:
void runApp() {
String str = "345, 688"; //->"345" "688"
String value = strCut(str);
}
String strCut(String str) {
int result = 0;
for (int i = 0; i < str.length(); i++) {
int cutStringIndex;
if (str.charAt(i) == ',') {
cutStringIndex = i;
}
for (int i = 0; i < cutStringIndex(); i++) {
String cutStringOne = "";
cutStringOne = cutStringOne + str.charAt(i);
}
for (int i = cutStringIndex() + 1; i < str.length(); i++) {
String cutStringTwo = "";
cutStringTwo = cutStringTwo + str.charAt(i);
}
cutString = cutStringOne + " " + cutStringTwo;
return cutString;
}
This will take out the comma which appears to be what you were looking for. I only used the two methods you asked for. Essentially this code gets the index of the comma, then reconstructs the two parts of the strings until it reaches the point of the comma, and skips over it. It may need some minor tweaks for your situation but this should be what you're looking for.
It can be done like this, Suppose String s="200,300,450,600" and you have to split given string using charAt() and string.length() method then first add ',' at the end of the string as given in the code below.
String s="200,300,450,600,",str="";
for(int i=0;i<s.length();i++){
char ch=s.charAt(i);
if(ch!=','){ //checking if particular character is not ','
str+=ch; //storing it in str string
}
else{
System.out.println(str); //printing each string before ',' is found
str="";
}
}
The output of above code will be:200
300
450
600(all the numbers will be printed on next line)
If you want to use only charAt and string.length() then you should try this
void runApp{
String str = "345, 688, 123";
String values[] = strCut(str); //values[0] = 345, values[1] = 688, values[2] = 123
for(String value : values){
System.out.print(value + " ");
}
}
String[] strCut(String str) {
int elements = 1;
int index = 0;
for(int i = 0; i < str.length(); i++){
if(str.charAt(i) == ',')
elements++;
}
String result[] = new String[elements];
for(int i = 0; i < result.length; i++)
result[i] = "";
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) != ',') {
if(str.charAt(i) != ' ')
result[index] = result[index] + str.charAt(i);
}
else index++;
}
return result;
}
You can do it as follows:
public class Main {
public static void main(String[] args) {
// Test
runApp();
}
static void runApp() {
String str = "345, 688"; // Expected->"345" "688"
String value = strCut(str);
System.out.println(value);// Display the result
}
static String strCut(String str) {
// Initialise result with a "
String result = "\"";
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ',') {// Check char at the index, i
// Add " at the end of one number and again " at the start of the next
result += "\" \"";
} else if (str.charAt(i) != ' ') {
result += str.charAt(i);
}
}
// Add " at the end
result += "\"";
// Finally, return result
return result;
}
}
Output:
"345" "688"
if you must want to make use of charAt() then do like below..
ArrayList<String> stringArr= new ArrayList<String>();
int startindex=0;
for (int i = 0; i < str.length(); i++)
{
if (str.charAt(i) == ',')
{
String partString = str.substring(startindex, i) ;
startindex=i+1;
stringArr.add(partString);
}
}
String lastString = str.substring(startindex, str.length()) ;
stringArr.add(lastString);
OR
You can simply use split method like below
String[] parts = string.split(",");
String part1 = parts[0]; // 345
String part2 = parts[1]; // 688
You can achieve it by simply doing this,
This will give you the desired result.
String str = "345,688";
ArrayList<String> stringArray = new ArrayList<>();
int startindex=0;
for (int i = 0; i < str.length(); i++) {
if(str.charAt(i) == ',') {
String subStr = str.substring(startindex, i);
startindex = i+1;
stringArray.add(subStr);
}
}
stringArray.add(str.substring(startindex));

parsing/converting task with characters and numbers within

It is necessary to repeat the character, as many times as the number behind it.
They are positive integer numbers.
case #1
input: "abc3leson11"
output: "abccclesonnnnnnnnnnn"
I already finish it in the following way:
String a = "abbc2kd3ijkl40ggg2H5uu";
String s = a + "*";
String numS = "";
int cnt = 0;
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (Character.isDigit(ch)) {
numS = numS + ch;
cnt++;
} else {
cnt++;
try {
for (int j = 0; j < Integer.parseInt(numS); j++) {
System.out.print(s.charAt(i - cnt));
}
if (i != s.length() - 1 && !Character.isDigit(s.charAt(i + 1))) {
System.out.print(s.charAt(i));
}
} catch (Exception e) {
if (i != s.length() - 1 && !Character.isDigit(s.charAt(i + 1))) {
System.out.print(s.charAt(i));
}
}
cnt = 0;
numS = "";
}
}
But I wonder is there some better solution with less and cleaner code?
Could you take a look below? I'm using a library from StringUtils from Apache Common Utils to repeat character:
public class MicsTest {
public static void main(String[] args) {
String input = "abc3leson11";
String output = input;
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(input);
while (m.find()) {
int number = Integer.valueOf(m.group());
char repeatedChar = input.charAt(m.start()-1);
output = output.replaceFirst(m.group(), StringUtils.repeat(repeatedChar, number));
}
System.out.println(output);
}
}
In case you don't want to use StringUtils. You can use the below custom method to achieve the same effect:
public static String repeat(char c, int times) {
char[] chars = new char[times];
Arrays.fill(chars, c);
return new String(chars);
}
Using java basic string regx should make it more terse as follows:
public class He1 {
private static final Pattern pattern = Pattern.compile("[a-zA-Z]+(\\d+).*");
// match the number between or the last using regx;
public static void main(String... args) {
String s = "abc3leson11";
System.out.println(parse(s));
s = "abbc2kd3ijkl40ggg2H5uu";
System.out.println(parse(s));
}
private static String parse(String s) {
Matcher matcher = pattern.matcher(s);
while (matcher.find()) {
int num = Integer.valueOf(matcher.group(1));
char prev = s.charAt(s.indexOf(String.valueOf(num)) - 1);
// locate the char before the number;
String repeated = new String(new char[num-1]).replace('\0', prev);
// since the prev is not deleted, we have to decrement the repeating number by 1;
s = s.replaceFirst(String.valueOf(num), repeated);
matcher = pattern.matcher(s);
}
return s;
}
}
And the output should be:
abccclesonnnnnnnnnnn
abbcckdddijkllllllllllllllllllllllllllllllllllllllllggggHHHHHuu
String g(String a){
String result = "";
String[] array = a.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
//System.out.println(java.util.Arrays.toString(array));
for(int i=0; i<array.length; i++){
String part = array[i];
result += part;
if(++i == array.length){
break;
}
char charToRepeat = part.charAt(part.length() - 1);
result += repeat(charToRepeat+"", new Integer(array[i]) - 1);
}
return result;
}
// In Java 11 this could be removed and replaced with the builtin `str.repeat(amount)`
String repeat(String str, int amount){
return new String(new char[amount]).replace("\0", str);
}
Try it online.
Explanation:
The split will split the letters and numbers:
abbc2kd3ijkl40ggg2H5uu would become ["abbc", "2", "kd", "3", "ijkl", "40", "ggg", "2", "H", "5", "uu"]
We then loop over the parts and add any strings as is to the result.
We then increase i by 1 first and if we're done (after the "uu") in the array above, it will break the loop.
If not the increase of i will put us at a number. So it will repeat the last character of the part x amount of times, where x is the number we found minus 1.
Here is another solution:
String str = "abbc2kd3ijkl40ggg2H5uu";
String[] part = str.split("(?<=\\d)(?=\\D)|(?=\\d)(?<=\\D)");
String res = "";
for(int i=0; i < part.length; i++){
if(i%2 == 0){
res = res + part[i];
}else {
res = res + StringUtils.repeat(part[i-1].charAt(part[i-1].length()-1),Integer.parseInt(part[i])-1);
}
}
System.out.println(res);
Yet another solution :
public static String getCustomizedString(String input) {
ArrayList<String > letters = new ArrayList<>(Arrays.asList(input.split("(\\d)")));
letters.removeAll(Arrays.asList(""));
ArrayList<String > digits = new ArrayList<>(Arrays.asList(input.split("(\\D)")));
digits.removeAll(Arrays.asList(""));
for(int i=0; i< digits.size(); i++) {
int iteration = Integer.valueOf(digits.get(i));
String letter = letters.get(i);
char c = letter.charAt(letter.length()-1);
for (int j = 0; j<iteration -1 ; j++) {
letters.set(i,letters.get(i).concat(String.valueOf(c)));
}
}
String finalResult = "";
for (String str : letters) {
finalResult += str;
}
return finalResult;
}
The usage:
public static void main(String[] args) {
String testString1 = "abbc2kd3ijkl40ggg2H5uu";
String testString2 = "abc3leson11";
System.out.println(getCustomizedString(testString1));
System.out.println(getCustomizedString(testString2));
}
And the result:
abbcckdddijkllllllllllllllllllllllllllllllllllllllllggggHHHHHuu
abccclesonnnnnnnnnnn

how to convert "user_id" to "userId" in Java? [duplicate]

This question already has answers here:
What is the simplest way to convert a Java string from all caps (words separated by underscores) to CamelCase (no word separators)?
(22 answers)
Closed 7 years ago.
convert string to camelCase
eg:
"user_id" to "userId"
"user_name" to "userName"
"country_province_city" to "countryProvinceCity"
how to do that in a easy way?
ps:"country_province_city" should be "countryProvinceCity" not "countryprovincecity"
I would use a loop and a StringBuilder. Something like
String[] arr = { "user_id", "user_name", "country_province_city" };
for (String str : arr) {
StringBuilder sb = new StringBuilder(str);
int pos;
while ((pos = sb.indexOf("_")) > -1) {
String ch = sb.substring(pos + 1, pos + 2);
sb.replace(pos, pos + 2, ch.toUpperCase());
}
System.out.printf("%s = %s%n", str, sb);
}
And I get the (requested)
user_id = userId
user_name = userName
country_province_city = countryProvinceCity
As Fast Snail mentions, simply use, for example, if String str = "user_id, user_name, user_id";, call str = str.replaceAll("userID", "user_id");, causing str to now have the value "userID, user_name, userID"
Alternatively, a more complete method would be as follows
public String toCamel(String str) {
String[] splits = str.split("_");
for (int i = 1; i < splits.length; i++) {
char first = Character.toUpperCase(splits.charAt(0));
if (splits[i].length() > 0)
splits[i] = first + splits[i].substring(1);
else
splits[i] = first + "";
}
String toRet = "";
for (String s : splits)
toRet += s;
return toRet;
}
This is a very simple one:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String result = "";
String input = scan.nextLine();
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == '_') {
result += input.toUpperCase().charAt(i + 1);
i = i + 1;
} else {
result += input.toLowerCase().charAt(i);
}
}
System.out.println(result);
}
if you like to do it many times, I advice you to use a while loop to keep repeating the same code over and over again:
while (true) {
//the previous code
}
http://commons.apache.org/proper/commons-lang/javadocs/api-3.4/index.html
String str="country_province_city";
wordUtils.capitalize(str, '_');
str=str.replaceAll("_", "");
output: countryProvinceCity
For another point of view that the answers above you can also do it with split function and two loops, like this:
String[] strings = {"user_id","user_name","country_province_city"};
for (int i = 0; i < strings.length; i++)
{
String string = strings[i];
String totalString = "";
String[] divide = string.split("_");
for(int j = 0; j < divide.length; j++)
{
if(j != 0)
{
divide[j] = "" + divide[j].toUpperCase().charAt(0) + divide[j].substring(1,divide[j].length());
}
totalString = totalString + divide[j];
}
}
If you want to show this changed Strings by console you just have to add System.out.println after the second loop and inside the first one, like this:
for (int i = 0; i < strings.length; i++)
{
//The same code as the code that I put in the example above
for(int j = 0; j < divide.length; j++)
{
//The same code as the example above
}
System.out.println(totalString);
}
On the contrary, if your objective it's to store them into an array, you can do it like this:
String[] store;
for (int i = 0; i < strings.length; i++)
{
//The same code as the code that I put in the example above
store = new String[divide.length];
for(int j = 0; j < divide.length; j++)
{
//The same code as the example above
}
store[j] = totalString;
}
If you have any doubt about the code please let me know.
I expect it will help to you!

Finding patterns in strings using basic Java methods

say we have a string with these characters
"ABGCCFFGTBG"
then we have another string with characters "GECCCDOABG"
So the pattern is the prefix and suffix but if your given strings larger then this but have common prefix and suffix patterns how to pull those out into a substring in java. Keep in mind we dont always know the characters in the string were getting we just know there is a pattern in it.
my start is something like this
for(int i = 0. i < strA.length(); i++)
{
for(int j = 0; j < strB.length(); j++)
{
if(strA.charAt(i) == strB.charAt(j))
{
String subPattern = strA.substring(0,i);
String subPattern2 = strB.substring(0,j);
}
}
}
but this doesn't work. Any ideas?
Try to select best-matched pattern at first:
public static void main(String[] args) {
String strA = "ABGCCFFGTBG";
String strB = "GECCCDOABG";
System.out.println("Pattern: " + findPattern(strA, strB));
}
public static String findPattern(String strA, String strB) {
for (int length = Math.min(strA.length(), strB.length()); length > 0; length--) {
for (int i = 0; i <= strA.length() - length; i++) {
String pattern = strA.substring(i, i + length);
if (strB.contains(pattern)) {
return pattern;
}
}
}
throw new NoSuchElementException("No common pattern between " + strA + " and " + strB);
}
Output:
Pattern: ABG
this solution will find a pattern, no matter where it is in the string:
public static void main(String[] args) {
String strA = "uioABCDqwert";
String strB = "yxcvABCDwrk";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < strA.length(); i++) {
for (int j = 0; j < strB.length(); j++) {
if (strA.charAt(i) == strB.charAt(j)) {
sb.append(strB.charAt(j));
i++;
}
}
if (sb.length() > 0)
break;
}
System.out.println(sb.toString());
}
this should give you an idea how it could be done

Categories

Resources