java - Replace only the first specific occurrence -
i want replace spaces in parentheses. code changes spaces in string & don't know why. wrote code this.
public static void main(string[] args) { scanner scanner = new scanner(system.in); string line; line = scanner.nextline(); (int i=0; i<line.length(); i++){ if (line.charat(i)=='('){ while (line.charat(i)!=')'){ i++; if(line.charat(i)==' '){ line=line.replacefirst(" ", "-space-"); } } } } system.out.println(line); }
just replaced 1 line: spaces in parantheses changed.
public static void main(string[] args) { scanner scanner = new scanner(system.in); string line; line = scanner.nextline(); (int i=0; i<line.length(); i++){ if (line.charat(i)=='('){ while (line.charat(i)!=')'){ i++; if(line.charat(i)==' '){ // changed line = line.substring(0, i) + "-space-" + line.substring(i+1, line.length()); } } } } system.out.println(line); scanner.close(); }
Comments
Post a Comment