Replace spaces in strings

Source: Internet
Author: User

/***** Replace each space in the string with % 20. for example, if We are happy, the output We % 20are % 20 happy **/public class ReplaceSpace {public void repalce (char [] oldchar, char [] replacement) {int sumOfSpace = 0; for (int I = 0; I <oldchar. length; I ++) {if (oldchar [I] = '') sumOfSpace ++;} if (sumOfSpace = 0) {return ;} char [] newchar = new char [oldchar. length + (replacement. length-1) * sumOfSpace]; // point to the last element of the replaced string, int pOld = oldchar. length-1; // point to the last element of the replacement string, int pNew = newchar. length-1; while (pNew> = 0) {if (oldchar [pOld] = '') {pOld --; for (int j = replacement. length-1; j> = 0; j --) {newchar [pNew --] = replacement [j] ;}} else {newchar [pNew --] = oldchar [pOld --] ;}}for (char c: newchar) {System. out. print (c) ;}} public static void main (String [] args) {char [] ch = "We are happy ". toCharArray (); ReplaceSpace rs = new ReplaceSpace (); rs. repalce (ch, "% 20 ". toCharArray ());}}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.