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));
Related
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();
}
I am looking to implement a method to perform basic string compression in the form of:
aabcccccaaa -> a2b1c5a3
I have this program:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
System.out.println(compress(str));
}
public static String compress(String str) {
char[] chars = str.toCharArray();
int count = 0;
String result = "";
for (int i = 0; i < chars.length; i++) {
char curr = chars[i];
result += curr;
for (int j = i; j < chars.length; j++) {
if (chars[j] == curr) {
count++;
}
else {
i += count;
break;
}
}
result += count;
count = 0;
}
return result;
}
}
But in my tests I am always missing the last character count.
I assume this is because the program gets out of the inner for loop before it should, but why is this the case?
Thanks a lot
You don't need two for loops for this and can do it in one go like so
String str = "aaabbbbccccca";
char[] chars = str.toCharArray();
char currentChar = str.length() > 0 ? chars[0] : ' ';
char prevChar = ' ';
int count = 1;
StringBuilder finalString = new StringBuilder();
if(str.length() > 0)
for(int i = 1; i < chars.length; i++)
{
if(currentChar == chars[i])
{
count++;
}else{
finalString.append(currentChar + "" + count);
prevChar = currentChar;
currentChar = chars[i];
count = 1;
}
}
if(str.length() > 0 && prevChar != currentChar)
finalString.append(currentChar + "" + count);
System.out.println(finalString.toString());
Output is: a3b4c5a1 for aaabbbbccccca
Keep a track of character that you are reading and compare it with next character of the string. If it is different, reset the count.
public static void stringCompression (String compression) {
String finalCompressedString = "";
char current = '1';
int count = 0;
compression = compression + '1';
for (int i = 0; i < compression.length(); i++) {
if (compression.charAt(i) == current) {
count = count + 1;
} else {
if (current != '1')
finalCompressedString = finalCompressedString + (current + Integer.toString(count));
count = 1;
current = compression.charAt(i);
}
}
System.out.println(finalCompressedString);
}
My answer for String Compression in java.
In this what i have done is and what you should have done is that , Keep a record of the characters that that are coming for a specific number of times, do so by comparing the current character with the next character , and when the current and the next character become unequal reset the value of count and repeat the whole process again for the next different character.
Hope it helps!
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
int count = 0;
for (int i=0; i<str.length(); ++i) {
int j=i+1;
count=1;
while (j!=str.length() && str.charAt(i) == str.charAt(j)) {
count += 1;
j += 1;
i += 1;
}
System.out.print(str.charAt(i));
if (count > 1) {
System.out.print(count);
}
}
}
}
The goal of the following program is to delimitate the source string thanks to the separators "/" " " and ":". The expected output is 20 03 2016 17 30 but it yields only 20 03 2016 17, omitting the last element. Maybe some off-by-one error?
public static void main(String[] args) {
String source = "20/03/2016:17:30";
String sep = "/:";
String[] result = new String[5];
String str = "";
int index = 0;
for (int sourcePos = 0; sourcePos < source.length(); sourcePos++) {
int compt = 0;
for (int sepPos = 0; sepPos < sep.length(); sepPos++) {
if (source.charAt(sourcePos) == sep.charAt(sepPos)) compt++;
}
if (compt > 0) {
result[index] = str;
System.out.print(" " + result[index]);
if (index < result.length)
index++;
else
break;
str = "";
} else {
str = str + source.charAt(sourcePos);
}
}
}
You could simply use regex:
String[] result = source.split("/|:");
As for your code, the reason why you are off by one is that the main for loop is terminated before you reach if (compt > 0) for the last time. In other words, sourcePos < source.length() is false, before you can add the last str.
You could so something like:
for (int sourcePos = 0; sourcePos < source.length() ; sourcePos++) {
boolean compt = false;
for (int sepPos = 0; sepPos < sep.length(); sepPos++) {
if (source.charAt(sourcePos) == sep.charAt(sepPos)) {
compt = true;
break;
}
}
if (compt) {
result[index] = str;
index++;
str = "";
}
else if(sourcePos == source.length()-1) {
result[index] = str + source.charAt(sourcePos);
}
else {
str = str + source.charAt(sourcePos);
}
}
Since you asked for a solution without regex (cite "...but I meant to do it without regex")
public static void main(String[] args) {
String source = "20/03/2016:17:30";
String result = "";
String before = "";
for (int sourcePos=0; sourcePos < source.length(); sourcePos ++ ) {
if (java.lang.Character.isDigit(source.charAt(sourcePos))) {
result += before + source.charAt(sourcePos);
before = "";
} else {
before = " "; // space will be added only once on next digit
}
}
System.out.println(result);
}
Anything other than a digit is considered a separator, even if it is more than one character.
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!
Ok, so I am required to create a program that will replace a word in a string according to a string, and also given a replacement. (In this case replace UK with United Kingdom)
Below is my code, but it doesn't work
import java.util.*;
public class replace
{
public static void main(String[]args){
replace("The UK should not be written as uk", "UK", "United Kingdom");
}
static void replace(String input, String seed, String replacement){
String s = "";
ArrayList<String> bla = new ArrayList<String>();
for(int i = 0; i < input.length();i++){
if(input.charAt(i) != ' '){
s = s + input.charAt(i);
}
if(input.charAt(i) == ' ' || i+1 == input.length()){
bla.add(s);
s = "";
}
}
String out = "";
for(int i = 0; i < bla.size(); i++){
if(bla.get(i) == seed){
bla.set(i, replacement);
}
}
for(int i = 0; i < bla.size(); i++){
out = out + bla.get(i)+ " ";
}
System.out.println(out);
}
}
For some reason it's not replacing my variable with the replacement
String out = "";
for(int i = 0; i < bla.size(); i++){
if(bla.get(i) == seed){
bla.set(i, replacement);
}
}
Any ideas why this might be?
Thanks in advance
Replace:
if(bla.get(i) == seed)
With:
if(bla.get(i).equals(seed))
The first compares reference, the second equality.
You should also use a StringBuilder to concatanate Strings, and keep it inside the loop:
ArrayList<String> bla = new ArrayList<String>();
for(int i = 0; i < input.length(); i++) {
StringBuilder s = new StringBuilder();
if(input.charAt(i) != ' ')
s.append(input.charAt(i));
if(input.charAt(i) == ' ' || i+1 == input.length())
bla.add(s.toString());
}
Using a StringBuilder is more efficient.