一句话单词倒置

前端之家收集整理的这篇文章主要介绍了一句话单词倒置前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
两种方式,第一,通过指针;第二,通过数组下标
void LoopMove(char * l,char * r)
{
	char temp;
	while(l<r)
	{
		temp = *l;
		*l = *r;
		*r = temp;
		++l;
		--r;
	}
}

void ReverseStr(char * str)
{
	char *l,*r;
	r = str;
	l = str;
	LoopMove(l,r+strlen(str)-1);
	while(*r!='\0')
	{
		l = r+1;
		r = l;
		while(*r!=' ' && *r!='\0')
			++r;
		r = r-1;
		LoopMove(l,r);
		l = r+1;
		r = l;
	}
}

int main()
{
	char str[]="i come from tianjin.";
	cout<<strlen(str)<<endl;
	ReverseStr(str);
	cout<<str<<endl;
	return 0;
}


public class StrReverse {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String str="hello i tianjin.";
		char []s = str.tocharArray();
		reverseWord(s);
		System.out.println(new String(s));
	}
	
	public static void reverseWord(char []s){
		int l = 0;
		int r = 0;
		reverse(s,l,r+s.length-1);
		for(int i=0; i<=s.length;++i){
			if(i==(s.length)||s[i]==' '){//注意顺序,否则越界错误
				r = i-1;
				System.out.println(l+" "+r);
				reverse(s,r);
				System.out.println(new String(s));
				l = i+1;
			}
		}
	}
	
	public static void reverse(char []s,int l,int r){
		char temp;
		for(int i=0; i<=(r-l)/2; i++)
		{
			temp = s[l+i];
			s[l+i] = s[r-i];
			s[r-i] = temp;
		}
	}
}

猜你在找的设计模式相关文章