String loop Right shift Java algorithm __ algorithm

Source: Internet
Author: User

Enter a string, and then tell the string loop to move right 4 bits

such as input abcdefgh

The output EFGHABCD

Here are two methods, the first is to convert the string to a character array char[];

Import java.util.*;
Class move 
{public
	static void Main (string[] args) 
	{
		Scanner sc=new Scanner (system.in);
		String Str=sc.next ();
		Char[] Rt=new char[str.length ()];
		for (int i=0;i<str.length (); i++)		
		Rt[i]=str.charat (i);		
	for (int i=0;i<str.length (); i++)
	{
		if (i>str.length ()-5)
		rt[(i%4)]=str.charat (i);
		else Rt[i+4]=str.charat (i);
	}
		System.out.println (RT);
	}
Here is the second method, which uses the StringBuilder replace method to pass in the parameter start,end,replacement

Import java.util.*;
Class move 
{public
	static void Main (string[] args) 
	{
		Scanner sc=new Scanner (system.in);
		String Str=sc.next ();
		StringBuilder sb=new StringBuilder (str);
		for (int i=0;i<str.length (); i++)
		{
			if (i>str.length ()-5)
			Sb.replace (i%4, (i%4) +1,new String (new Char[]{str.charat (i)}));
		else
			sb.replace (i+4,i+5,new String (new Char[]{str.charat (i)}));
		System.out.println (SB);
	}

If you want to use the Replace method of string, it is not feasible to experiment, because the replace method of the string will only replace one part and cannot change the entire string to StringBuilder.


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.