As of now I'm using this code to make my first letter in a string capital
String output = input.substring(0, 1).toUpperCase() + input.substring(1);
This seems very dirty to me ..is there any direct or elegant way..
How about this:
String output = Character.toUpperCase(input.charAt(0)) + input.substring(1);
I can't think of anything cleaner without using external libraries, but this is definitely better than what you currently have.
You should have a look at StringUtils class from Apache Commons Lang lib - it has method .capitalize()
Description from the lib:
Capitalizes a String changing the first letter to title case as per
Character.toTitleCase(char). No other letters are changed.
String out = Character.toUpperCase(inText.charAt(0)) + inText.substring(1).toLowerCase();
public static void main(String[] args) {
String str = null;
String outStr = null;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a String: ");
str = sc.nextLine();
//c= Character.toUpperCase(str.charAt(0));
for(int i=0; i< (str.length());i++){
if(str.charAt(i)==' '){
outStr= outStr.substring(0,i+1)+str.substring(i+1,i+2).toUpperCase()+str.substring(i+2);
}else if(i==0){
outStr=str.substring(0,1).toUpperCase()+str.substring(1);
}
}
System.out.println("STRING::"+outStr);
}
Assuming you can use Java 8, here's the functional way that nobody asked for...
import java.util.Optional;
import java.util.stream.IntStream;
public class StringHelper {
public static String capitalize(String source) {
return Optional.ofNullable(source)
.map(str -> IntStream.concat(
str.codePoints().limit(1).map(Character::toUpperCase),
str.codePoints().skip(1)))
.map(stream -> stream.toArray())
.map(arr -> new String(arr, 0, arr.length))
.orElse(null);
}
}
It's elegant in that it handles the null and empty string cases without any conditional statements.
Character.toString(a.charAt(0)).toUpperCase()+a.substring(1)
P.S = a is string.
Here, hold my beer
String foo = "suresh";
String bar = foo.toUpperCase();
if(bar.charAt[0] == 'S'){
throw new SuccessException("bar contains 'SURESH' and has the first letter capital").
}
class strDemo3
{
public static void main(String args[])
{
String s1=new String(" the ghost of the arabean sea");
char c1[]=new char[30];
int c2[]=new int[30];
s1.getChars(0,28,c1,0);
for(int i=0;i<s1.length();i++)
{
System.out.print(c1[i]);
}
for(int i=1;i<s1.length();i++)
{
c2[i]=c1[i];
if(c1[i-1]==' ')
{
c2[i]=c2[i]-32;
}
c1[i]=(char)c2[i];
}
for(int i=0;i<s1.length();i++)
{
System.out.print(c1[i]);
}
}
}
Related
As of now I am making a small program that compares two string with the outcome of true and false. However, the program needs to say true if it visually looks the same. for example if it say box and b0x then it would be true. As of now the outcome is looking false as shown below.
Enter First String:
box
Enter Second String:
b0x
false
the string below needs to be considered the same
0, o and Q
1, I and T
2 and Z
5 and S
8 and B
below is my current work
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter First String:");
String str1 = sc.nextLine();
System.out.println("Enter Second String:");
String str2 = sc.nextLine();
sc.close();
String string1 = new String("0");
String string2 = new String("o");
String string3 = new String("q");
String string4 = new String("1");
String string5 = new String("l");
String string6 = new String("T");
String string7 = new String("2");
String string8 = new String("z");
String string9 = new String("5");
String string10 = new String("s");
String string11 = new String("8");
String string12 = new String("b");
// Comparing for String 3 = String 4
if (str1.equals(str2))
{
System.out.print(true);
}
else if(string1.equals(str1))
{
System.out.print(true);
}
else if(string2.equals(str2))
{
System.out.print(true);
}
else
{
System.out.print(false);
}
}
}
}
Is there any algorithm that I can use or any way where the program can detect as true even when they are visually the same. I appreciate any help, thank you
The answer to this question (as well as most questions about pattern matching in Strings) is regular expressions. All you need to do is use replaceAll for all your character transformations to normalize your strings.
like:
str1 = str1.replaceAll("[oQ]", 0);
str1 = str1.replaceAll("[IT]", 1);
First of all, when you declare String variables, you don't have to make a constructor call each time.
String string1 = "0" // that is fine. No need to call constructor.
Then, I advise you to create a collection of all the characters that are supposed to look the same.
Iterate over all the characters of the first input, and check if :
each character of the first input is equal to each character of the second input
if it is a "look visually the same character", check if second input contains the associated(s) character(s).
According to the data you provided, I suggest you this solution, though it is not the perfect one :
import javafx.util.Pair;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
private static List<List<Character>> charactersVisuallyLookingTheSame = new ArrayList<>();
public static void main(String[] args) {
initCharactersThatLookTheSame();
Scanner sc = new Scanner(System.in);
System.out.println("Enter First String:");
String str1 = sc.nextLine();
System.out.println("Enter Second String:");
String str2 = sc.nextLine();
sc.close();
boolean equal = equalsVisually(str1, str2);
System.out.println(equal);
}
private static boolean equalsVisually(String first, String second)
{
// some checks just in case...
if(first == null || second == null)
{
return false;
}
// to be equal visually, they must have the same length.
if(first.length() != second.length())
{
return false;
}
char[] firstAsArray = first.toCharArray();
char[] secondAsArray = second.toCharArray();
for(int i = 0; i < firstAsArray.length; i++)
{
// if it is different
if(firstAsArray[i] != secondAsArray[i])
{
if(!isCharVisuallyLookingTheSame(firstAsArray[i], secondAsArray[i]))
{
return false;
}
}
}
return true;
}
private static boolean isCharVisuallyLookingTheSame(char first, char second)
{
// we check if it looks visually the same
for(List<Character> visuallyTheSameList : charactersVisuallyLookingTheSame)
{
boolean doesFirstStringContainVisualChar = false;
for(Character c1 : visuallyTheSameList)
{
if(first == c1)
{
boolean doesSecondStringCharVisuallyEquals = false;
for(Character c2 : visuallyTheSameList)
{
if((second == c2))
{
return true;
}
}
}
}
}
return false;
}
private static void initCharactersThatLookTheSame()
{
// these lists contain all the characters that look visually the same.
// add in here any list of characters that visually look the same.
List<Character> o = new ArrayList<>();
charactersVisuallyLookingTheSame.add(o);
o.add('0');
o.add('o');
o.add('Q');
List<Character> i = new ArrayList<>();
charactersVisuallyLookingTheSame.add(i);
i.add('1');
i.add('I');
i.add('T');
List<Character> z = new ArrayList<>();
charactersVisuallyLookingTheSame.add(z);
z.add('2');
z.add('Z');
List<Character> S = new ArrayList<>();
charactersVisuallyLookingTheSame.add(S);
S.add('5');
S.add('S');
List<Character> B = new ArrayList<>();
charactersVisuallyLookingTheSame.add(B);
B.add('8');
B.add('B');
}
}
Some outputs :
I guess that will do the job. don't hesitate to execute it in debug mode if there are any problems. I fast coded this and I could have made mistakes.
But overall, I suggest you to : use regular expressions. It was suggested by another answer and I think that can only be better than this. Nevertheless, regular expressions can be hard to understand...
The other option would be to build a Map with a common Identifier between similar values. Might be a bit more complicated, but should be more performant than looping a replaceAll multiple times to normalize both values.
import java.util.HashMap;
import java.util.Map;
public class VisuallySimilar
{
public static int id = 0;
public static Map<Character, Integer> map = new HashMap<>();
public static void similarChars(Character... chars) {
for(Character c : chars) {
map.put(c, id);
}
id++;
}
public static boolean areSimilar(String val1, String val2) {
if(val1.length() != val2.length())
return false;
char[] char1 = val1.toCharArray();
char[] char2 = val2.toCharArray();
for(int i = 0; i < char1.length; i++) {
if(char1[i] == char2[i] || map.get(char1[i]) == map.get(char2[i]))
continue;
return false;
}
return true;
}
public static void main(String[] args) {
similarChars('0', 'o', 'O', 'Q');
similarChars('T', 'I', '1');
String val1 = "b0x";
String val2 = "box";
System.out.println("Are Similar: " + areSimilar(val1, val2));
}
}
newbie here. Any help with this problem would be appreciated:
You are given a String variable called data that contain letters and spaces only. Write the Java class to print a modified version of the String where all lowercase letters are replaced by ? and all whitespaces are replaced by +. An example is shown below: I Like Java becomes I+L???+J???.
What I have so far:
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
String data;
//prompt
System.out.println("Enter a sentence: ");
//input
data = input.nextLine();
for (int i = 0; i < data.length(); i++) {
if (Character.isWhitespace(data.charAt(i))) {
data.replace("", "+");
if (Character.isLowerCase(data.charAt(i))) {
data.replace(i, i++, ); //not sure what to include here
}
} else {
System.out.print(data);
}
}
}
any suggestions would be appreciated.
You can do it in two steps by chaining String#replaceAll. In the first step, replace the regex, [a-z], with ?. The regex, [a-z] means a character from a to z.
public class Main {
public static void main(String[] args) {
String str = "I Like Java";
str = str.replaceAll("[a-z]", "?").replaceAll("\\s+", "+");
System.out.println(str);
}
}
Output:
I+L???+J???
Alternatively, you can use a StringBuilder to build the desired string. Instead of using a StringBuilder variable, you can use String variable but I recommend you use StringBuilder for such cases. The logic of building the desired string is simple:
Loop through all characters of the string and check if the character is a lowercase letter. If yes, append ? to the StringBuilder instance else if the character is whitespace, append + to the StringBuilder instance else append the character to the StringBuilder instance as it is.
Demo:
public class Main {
public static void main(String[] args) {
String str = "I Like Java";
StringBuilder sb = new StringBuilder();
int len = str.length();
for (int i = 0; i < len; i++) {
char ch = str.charAt(i);
if (Character.isLowerCase(ch)) {
sb.append('?');
} else if (Character.isWhitespace(ch)) {
sb.append('+');
} else {
sb.append(ch);
}
}
// Assign the result to str
str = sb.toString();
// Display str
System.out.println(str);
}
}
Output:
I+L???+J???
If the requirement states:
The first character of each word is a letter (uppercase or lowercase) which needs to be left as it is.
Second character onwards can be any word character which needs to be replaced with ?.
All whitespace characters of the string need to be replaced with +.
you can do it as follows:
Like the earlier solution, chain String#replaceAll for two steps. In the first step, replace the regex, (?<=\p{L})\w, with ?. The regex, (?<=\p{L})\w means:
\w specifies a word character.
(?<=\p{L}) specifies a positive lookbeghind for a letter i.e. \p{L}.
In the second step, simply replace one or more whitespace characters i.e. \s+ with +.
Demo:
public class Main {
public static void main(String[] args) {
String str = "I like Java";
str = str.replaceAll("(?<=\\p{L})\\w", "?").replaceAll("\\s+", "+");
System.out.println(str);
}
}
Output:
I+l???+J???
Alternatively, again like the earlier solution you can use a StringBuilder to build the desired string. Loop through all characters of the string and check if the character is a letter. If yes, append it to the StringBuilder instance and then loop through the remaining characters until all characters are exhausted or a space character is encountered. If a whitespace character is encountered, append + to the StringBuilder instance else append ? to it.
Demo:
public class Main {
public static void main(String[] args) {
String str = "I like Java";
StringBuilder sb = new StringBuilder();
int len = str.length();
for (int i = 0; i < len; i++) {
char ch = str.charAt(i++);
if (Character.isLetter(ch)) {
sb.append(ch);
while (i < len && !Character.isWhitespace(ch = str.charAt(i))) {
sb.append('?');
i++;
}
if (Character.isWhitespace(ch)) {
sb.append('+');
}
}
}
// Assign the result to str
str = sb.toString();
// Display str
System.out.println(str);
}
}
Output:
I+l???+J???
package com.company;
import java.util.*;
public class dat {
public static void main(String[] args) {
System.out.println("enter the string:");
Scanner ss = new Scanner(System.in);
String data = ss.nextLine();
for (int i = 0; i < data.length(); i++) {
char ch = data.charAt(i);
if (Character.isWhitespace(ch))
System.out.print("+");
else if (Character.isLowerCase(ch))
System.out.print("?");
else
System.out.print(ch);
}
}
}
enter the string:
i Love YouU
?+L???+Y??U
Firstly, you are trying to make changes to String object which is immutable. Simple way to achieve what you want is convert string to character array and loop over array items:
Scanner input = new Scanner(System.in);
String data;
//prompt
System.out.println("Enter a sentence: ");
//input
data = input.nextLine();
char[] dataArray = data.toCharArray();
for (int i = 0; i < dataArray.length; i++) {
if (Character.isWhitespace(dataArray[i])) {
dataArray[i] = '+';
} else if (Character.isLowerCase(dataArray[i])) {
dataArray[i] = '?';
}
}
System.out.print(dataArray);
See the below code and figure out what's wrong in your code. To include multiple regex put the char within square brackets:
import java.util.Scanner;
public class mainClass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String data = input.nextLine();
String one = data.replaceAll(" ", "+");
String two = one.replaceAll("[a-z]", "?");
System.out.println(two);
}
}
You can use String.codePoints method to get a stream over int values of characters of this string, and process them:
private static String replaceCharacters(String str) {
return str.codePoints()
.map(ch -> {
if (Character.isLowerCase(ch))
return '?';
if (Character.isWhitespace(ch))
return '+';
return ch;
})
.mapToObj(Character::toString)
.collect(Collectors.joining());
}
public static void main(String[] args) {
System.out.println(replaceCharacters("Lorem ipsum")); // L????+?????
System.out.println(replaceCharacters("I Like Java")); // I+L???+J???
}
See also: Replace non ASCII character from string
How to check if a string contains only letters? is there any specific functions that does that ?
I don't know about a direct function But you can follow these steps :
1) Take a string as input
2) By using toLower() method, convert everything into lower case
3) Use toCharArray() method of the String class to convert into a character array
4) Now check whether at every location has character between a to z
code :
import java.util.Scanner;
public class StringValidation{
public boolean validtaeString(String str) {
str = str.toLowerCase();
char[] charArray = str.toCharArray();
for (int i = 0; i < charArray.length; i++) {
char ch = charArray[i];
if (!(ch >= 'a' && ch <= 'z')) {
return false;
}
}
return true;
}
public static void main(String args[]) {
Scanner sc= new Scanner(System.in);
System.out.println("Enter a string value: ");
String str = sc.next();
StringValidation obj = new StringValidation();
boolean bool = obj.validtaeString(str);
if(!bool) {
System.out.println("Given String is invalid");
}else{
System.out.println("Given String is valid");
}
}
}
Here is the output:
Output:
Enter a string value:
24stackoverflow
Given String is invalid
------------------------
Enter a string value:
StackOverflow
Given String is valid
You can use a regex to test if a string matches the pattern /^[a-z]+$/i if you're only concerned about simple English unaccented letters.
For letters in many languages, you can use /^\p{L}+$/i.
As Java regexes, these look like:
Pattern.compile("^[a-z]+$", Pattern.CASE_INSENSITIVE)
Pattern.compile("^\\p{L}+$")
Update: {L} works better than {Alpha} for accented characters.
pattern = Pattern.compile("^\\p{L}+$");
System.out.println(pattern.matcher("foo").matches());
System.out.println(pattern.matcher("Foo").matches());
System.out.println(pattern.matcher("föo").matches());
System.out.println(pattern.matcher("fo-oo").matches());
Try StringUtils.isAlpha.
See: http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#isAlpha-java.lang.CharSequence-
I see the answer and I want to add another solution, I preferred this solution because is more personalizable.
The class Character has the method, like.isLetter(). you can see also the java documentation
I have a code example like this:
public class CheckLetterInTheString {
public static boolean isOnlyLetter(String string){
if(string == null || string.isEmpty()){
throw new IllegalArgumentException("String not valid");
}
char[] chatString = string.toCharArray();
for(Character character : chatString){
if(!Character.isLetter(character) && !Character.isSpaceChar(character)){
return false;
}
}
return true;
}
}
now you can call
System.out.println(CheckLetterInTheString.isOnlyLetter("String only letter")); //true
System.out.println(CheckLetterInTheString.isOnlyLetter("Contains num 12")); //false
P.S: I like this solution because is more personalizable and I think it is more readable than a regex. But is only my opinion
I'd like to do a function which gets a string and in case it has inline comments it removes it. I know it sounds pretty simple but i wanna make sure im doing this right, for example:
private String filterString(String code) {
// lets say code = "some code //comment inside"
// return the string "some code" (without the comment)
}
I thought about 2 ways: feel free to advice otherwise
Iterating the string and finding double inline brackets and using substring method.
regex way.. (im not so sure bout it)
can u tell me what's the best way and show me how it should be done? (please don't advice too advanced solutions)
edited: can this be done somehow with Scanner object? (im using this object anyway)
If you want a more efficient regex to really match all types of comments, use this one :
replaceAll("(?:/\\*(?:[^*]|(?:\\*+[^*/]))*\\*+/)|(?://.*)","");
source : http://ostermiller.org/findcomment.html
EDIT:
Another solution, if you're not sure about using regex is to design a small automata like follows :
public static String removeComments(String code){
final int outsideComment=0;
final int insideLineComment=1;
final int insideblockComment=2;
final int insideblockComment_noNewLineYet=3; // we want to have at least one new line in the result if the block is not inline.
int currentState=outsideComment;
String endResult="";
Scanner s= new Scanner(code);
s.useDelimiter("");
while(s.hasNext()){
String c=s.next();
switch(currentState){
case outsideComment:
if(c.equals("/") && s.hasNext()){
String c2=s.next();
if(c2.equals("/"))
currentState=insideLineComment;
else if(c2.equals("*")){
currentState=insideblockComment_noNewLineYet;
}
else
endResult+=c+c2;
}
else
endResult+=c;
break;
case insideLineComment:
if(c.equals("\n")){
currentState=outsideComment;
endResult+="\n";
}
break;
case insideblockComment_noNewLineYet:
if(c.equals("\n")){
endResult+="\n";
currentState=insideblockComment;
}
case insideblockComment:
while(c.equals("*") && s.hasNext()){
String c2=s.next();
if(c2.equals("/")){
currentState=outsideComment;
break;
}
}
}
}
s.close();
return endResult;
}
The best way to do this is to use regular expressions.
At first to find the /**/ comments and then remove all // commnets. For example:
private String filterString(String code) {
String partialFiltered = code.replaceAll("/\\*.*\\*/", "");
String fullFiltered = partialFiltered.replaceAll("//.*(?=\\n)", "")
}
Just use the replaceAll method from the String class, combined with a simple regular expression. Here's how to do it:
import java.util.*;
import java.lang.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
String s = "private String filterString(String code) {\n" +
" // lets say code = \"some code //comment inside\"\n" +
" // return the string \"some code\" (without the comment)\n}";
s = s.replaceAll("//.*?\n","\n");
System.out.println("s=" + s);
}
}
The key is the line:
s = s.replaceAll("//.*?\n","\n");
The regex //.*?\n matches strings starting with // until the end of the line.
And if you want to see this code in action, go here: http://www.ideone.com/e26Ve
Hope it helps!
To find the substring before a constant substring using a regular expression replacement is a bit much.
You can do it using indexOf() to check for the position of the comment start and substring() to get the first part, something like:
String code = "some code // comment";
int offset = code.indexOf("//");
if (-1 != offset) {
code = code.substring(0, offset);
}
#Christian Hujer has been correctly pointing out that many or all of the solutions posted fail if the comments occur within a string.
#Loïc Gammaitoni suggests that his automata approach could easily be extended to handle that case. Here is that extension.
enum State { outsideComment, insideLineComment, insideblockComment, insideblockComment_noNewLineYet, insideString };
public static String removeComments(String code) {
State state = State.outsideComment;
StringBuilder result = new StringBuilder();
Scanner s = new Scanner(code);
s.useDelimiter("");
while (s.hasNext()) {
String c = s.next();
switch (state) {
case outsideComment:
if (c.equals("/") && s.hasNext()) {
String c2 = s.next();
if (c2.equals("/"))
state = State.insideLineComment;
else if (c2.equals("*")) {
state = State.insideblockComment_noNewLineYet;
} else {
result.append(c).append(c2);
}
} else {
result.append(c);
if (c.equals("\"")) {
state = State.insideString;
}
}
break;
case insideString:
result.append(c);
if (c.equals("\"")) {
state = State.outsideComment;
} else if (c.equals("\\") && s.hasNext()) {
result.append(s.next());
}
break;
case insideLineComment:
if (c.equals("\n")) {
state = State.outsideComment;
result.append("\n");
}
break;
case insideblockComment_noNewLineYet:
if (c.equals("\n")) {
result.append("\n");
state = State.insideblockComment;
}
case insideblockComment:
while (c.equals("*") && s.hasNext()) {
String c2 = s.next();
if (c2.equals("/")) {
state = State.outsideComment;
break;
}
}
}
}
s.close();
return result.toString();
}
I made an open source library (on GitHub) for this purpose , its called CommentRemover you can remove single line and multiple line Java Comments.
It supports remove or NOT remove TODO's.
Also it supports JavaScript , HTML , CSS , Properties , JSP and XML Comments too.
Little code snippet how to use it (There is 2 type usage):
First way InternalPath
public static void main(String[] args) throws CommentRemoverException {
// root dir is: /Users/user/Projects/MyProject
// example for startInternalPath
CommentRemover commentRemover = new CommentRemover.CommentRemoverBuilder()
.removeJava(true) // Remove Java file Comments....
.removeJavaScript(true) // Remove JavaScript file Comments....
.removeJSP(true) // etc.. goes like that
.removeTodos(false) // Do Not Touch Todos (leave them alone)
.removeSingleLines(true) // Remove single line type comments
.removeMultiLines(true) // Remove multiple type comments
.startInternalPath("src.main.app") // Starts from {rootDir}/src/main/app , leave it empty string when you want to start from root dir
.setExcludePackages(new String[]{"src.main.java.app.pattern"}) // Refers to {rootDir}/src/main/java/app/pattern and skips this directory
.build();
CommentProcessor commentProcessor = new CommentProcessor(commentRemover);
commentProcessor.start();
}
Second way ExternalPath
public static void main(String[] args) throws CommentRemoverException {
// example for externalPath
CommentRemover commentRemover = new CommentRemover.CommentRemoverBuilder()
.removeJava(true) // Remove Java file Comments....
.removeJavaScript(true) // Remove JavaScript file Comments....
.removeJSP(true) // etc..
.removeTodos(true) // Remove todos
.removeSingleLines(false) // Do not remove single line type comments
.removeMultiLines(true) // Remove multiple type comments
.startExternalPath("/Users/user/Projects/MyOtherProject")// Give it full path for external directories
.setExcludePackages(new String[]{"src.main.java.model"}) // Refers to /Users/user/Projects/MyOtherProject/src/main/java/model and skips this directory.
.build();
CommentProcessor commentProcessor = new CommentProcessor(commentRemover);
commentProcessor.start();
}
for scanner, use a delimiter,
delimiter example.
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class MainClass {
public static void main(String args[]) throws IOException {
FileWriter fout = new FileWriter("test.txt");
fout.write("2, 3.4, 5,6, 7.4, 9.1, 10.5, done");
fout.close();
FileReader fin = new FileReader("Test.txt");
Scanner src = new Scanner(fin);
// Set delimiters to space and comma.
// ", *" tells Scanner to match a comma and zero or more spaces as
// delimiters.
src.useDelimiter(", *");
// Read and sum numbers.
while (src.hasNext()) {
if (src.hasNextDouble()) {
System.out.println(src.nextDouble());
} else {
break;
}
}
fin.close();
}
}
Use a tokenizer for a normal string
tokenizer:
// start with a String of space-separated words
String tags = "pizza pepperoni food cheese";
// convert each tag to a token
StringTokenizer st = new StringTokenizer(tags," ");
while ( st.hasMoreTokens() )
{
String token = (String)st.nextToken();
System.out.println(token);
}
http://www.devdaily.com/blog/post/java/java-faq-stringtokenizer-example
It will be better if code handles single line comment and multi line comment separately . Any suggestions ?
public class RemovingCommentsFromFile {
public static void main(String[] args) throws IOException {
BufferedReader fin = new BufferedReader(new FileReader("/home/pathtofilewithcomments/File"));
BufferedWriter fout = new BufferedWriter(new FileWriter("/home/result/File1"));
boolean multilinecomment = false;
boolean singlelinecomment = false;
int len,j;
String s = null;
while ((s = fin.readLine()) != null) {
StringBuilder obj = new StringBuilder(s);
len = obj.length();
for (int i = 0; i < len; i++) {
for (j = i; j < len; j++) {
if (obj.charAt(j) == '/' && obj.charAt(j + 1) == '*') {
j += 2;
multilinecomment = true;
continue;
} else if (obj.charAt(j) == '/' && obj.charAt(j + 1) == '/') {
singlelinecomment = true;
j = len;
break;
} else if (obj.charAt(j) == '*' && obj.charAt(j + 1) == '/') {
j += 2;
multilinecomment = false;
break;
} else if (multilinecomment == true)
continue;
else
break;
}
if (j == len)
{
singlelinecomment=false;
break;
}
else
i = j;
System.out.print((char)obj.charAt(i));
fout.write((char)obj.charAt(i));
}
System.out.println();
fout.write((char)10);
}
fin.close();
fout.close();
}
Easy solution that doesn't remove extra parts of code (like those above)
// works for any reader, you can also iterate over list of strings instead
String str="";
String s;
while ((s = reader.readLine()) != null)
{
s=s.replaceAll("//.*","\n");
str+=s;
}
str=str.replaceAll("/\\*.*\\*/"," ");
How do I split strings in J2ME in an effective way?
There is a StringTokenizer or String.split(String regex) in the standard edition (J2SE), but they are absent in the micro edition (J2ME, MIDP).
There are a few implementations of a StringTokenizer class for J2ME. This one by Ostermiller will most likely include the functionality you need
See also this page on Mobile Programming Pit Stop for some modifications and the following example:
String firstToken;
StringTokenizer tok;
tok = new StringTokenizer("some|random|data","|");
firstToken= tok.nextToken();
There is no built in method to split strings. You have to write it on your own using
String.indexOf() and String.substring(). Not hard.
String.split(...) is available in J2SE, but not J2ME.
You are required to write your own algorithm: related post with sample solution.
I hope this one will help you... This is my own implementation i used in my application. Of course this can still be optimized. i just do not have time to do it... and also, I am working on StringBuffer here. Just refactor this to be able to use String instead.
public static String[] split(StringBuffer sb, String splitter){
String[] strs = new String[sb.length()];
int splitterLength = splitter.length();
int initialIndex = 0;
int indexOfSplitter = indexOf(sb, splitter, initialIndex);
int count = 0;
if(-1==indexOfSplitter) return new String[]{sb.toString()};
while(-1!=indexOfSplitter){
char[] chars = new char[indexOfSplitter-initialIndex];
sb.getChars(initialIndex, indexOfSplitter, chars, 0);
initialIndex = indexOfSplitter+splitterLength;
indexOfSplitter = indexOf(sb, splitter, indexOfSplitter+1);
strs[count] = new String(chars);
count++;
}
// get the remaining chars.
if(initialIndex+splitterLength<=sb.length()){
char[] chars = new char[sb.length()-initialIndex];
sb.getChars(initialIndex, sb.length(), chars, 0);
strs[count] = new String(chars);
count++;
}
String[] result = new String[count];
for(int i = 0; i<count; i++){
result[i] = strs[i];
}
return result;
}
public static int indexOf(StringBuffer sb, String str, int start){
int index = -1;
if((start>=sb.length() || start<-1) || str.length()<=0) return index;
char[] tofind = str.toCharArray();
outer: for(;start<sb.length(); start++){
char c = sb.charAt(start);
if(c==tofind[0]){
if(1==tofind.length) return start;
inner: for(int i = 1; i<tofind.length;i++){ // start on the 2nd character
char find = tofind[i];
int currentSourceIndex = start+i;
if(currentSourceIndex<sb.length()){
char source = sb.charAt(start+i);
if(find==source){
if(i==tofind.length-1){
return start;
}
continue inner;
} else {
start++;
continue outer;
}
} else {
return -1;
}
}
}
}
return index;
}
That depends on what exactly you want to achieve, but the function String.substring() will be in there somewhere:
String myString = "Hello World";
This will print the substring starting from index 6 to the end of the string:
System.out.println(myString.substring(6));
This will print the substring starting from index 0 until index 5:
System.out.println(myString.substring(0,5));
Output of all the code above:
World
Hello
Combine this with the other String functions (indexOf(). etc.) to achieve the desired effect!
Re-reading your question, it looks as though you may have been looking for String.split(). This will split your input string into an array of strings based on a given regex:
String myString = "Hi-There-Gang";
String[] splitStrings = myString.split("-");
This will result in the splitStrings array containing three string, "Hi", "There" and "Gang".
Re-reading your question again, String.split is not available in J2ME, but the same effect can be achieved with substring and indexOf.
public static Vector splitDelimiter(String text, char delimiter) {
Vector splittedString = null;
String text1 = "";
if (text != null) {
splittedString = new Vector();
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == delimiter) {
splittedString.addElement(text1);
text1 = "";
} else {
text1 += text.charAt(i);
// if(i==text.length()-1){
// splittedString.addElement(text1);
// }
}
}
splittedString.addElement(text1);
}
return s
}
You can use this method for splitting a delimiter.
In J2ME no split, but you can use this code for split.This code works with only 1 simbol delimiter!!!
Use NetBeans.File\Create Project\ Java ME\ MobileApplication\Set project name(split)\Set checkmark.Delete all code in your (Midlet.java).Copy this code and past in your (Midlet.java).
//IDE NetBeans 7.3.1
//author: UserSuperPupsik
//email: usersuperpupsik#gmail.com
package split;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import java.util.Vector;
public class Midlet extends MIDlet {
public String e1;
public Vector v=new Vector();
public int ma;
int IsD=0;
int vax=0;
public String out[];
private Form f;
public void split0(String text,String delimiter){
if (text!=""){
IsD=0;
int raz=0;
//v.removeAllElements();
v.setSize(0);
int io;
String temp="";
int ni=(text.length()-1);
for(io=0;io<=ni;io++){
char ch=text.charAt(io);
String st=""+ch;
if(io==0 && st.equals(delimiter)){IsD=1;}
if(!st.equals(delimiter)){temp=temp+st;} //Not equals (!=)
else if(st.equals(delimiter)&&temp!="")//equals (==)
{
IsD=1;
//f.append(temp);
v.addElement(temp);
temp="";
}
if(io==ni && temp!="") {
v.addElement(temp);
temp="";
}
if((io==ni)&&IsD==0&&temp!=""){v.addElement(temp);}
}
if(v.size()!=0){
ma=(v.size());
out=new String[ma];
v.copyInto(out);
}
//else if(v.size()==0){IsD=1; }
}
}
public void method1(){
f.append("\n");
f.append("IsD: " +IsD+"");
if (v.size()!=0){
for( vax=0;vax<=ma-1;vax++){
f.append("\n");
f.append(out[vax]);
}
}
}
public void startApp() {
f=new Form("Hello J2ME!");
Display.getDisplay(this).setCurrent(f);
f.append("");
split0("Hello.World.Good...Luck.end" , ".");
method1();
split0(".",".");
method1();
split0(" First WORD2 Word3 "," ");
method1();
split0("...",".");
method1();
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}
Splited elements located in array called (out).For Example out[1]:Hello.
Good Luck!!!
Another alternative solution:
public static Vector split(String stringToSplit, String separator){
if(stringToSplit.length<1){
return null;
}
Vector stringsFound = new Vector();
String remainingString = stringToSplit;
while(remainingString.length()>0){
int separatorStartingIndex = remainingString.indexOf(separator);
if(separatorStartingIndex==-1){
// Not separators found in the remaining String. Get substring and finish
stringsFound.addElement(remainingString);
break;
}
else{
// The separator is at the beginning of the String,
// Push the beginning at the end of separator and continue
if(remainingString.startsWith(separator)){
remainingString = remainingString.substring(separator.length());
}
// The separator is present and is not the beginning, add substring and continue
else{
stringsFound.addElement(remainingString.substring(0, separatorStartingIndex));
remainingString = remainingString.substring(separatorStartingIndex + separator.length());
}
}
}
return stringsFound;
}