输入一个英文句子,翻转句子中的单词,要求单词内的字符顺序不变。 如:I am a student. 转换成 student. a am I

输入一个英文句子,翻转句子中的单词,要求单词内的字符顺序不变。

如:I am a student. 转换成 student. a am I 

算法分析:

1、通过ReverseString(s,0,5)交换字符串第0位和第5位的字符,将I am a student. 转换成a am I student.

2、然后将字符向左移动一位变成 am I student.a

3、顺序向左移动7次就成为了student. a am I 

#include "iostream"
#include <stdio.h>
using namespace std;

void ReverseString(char *s,int from,int to)
 {
   //交换from和to位置的字符
     if(from<to)
     {
         char t = s[from];
         s[from] = s[to];
         s[to] = t; 
     }
 }
 void LeftShiftOne(char *s,int n)
 {   //字符串向左移动一位,最左边一个字符放到最右边
     char t=s[0];
     for(int i=1; i<n ;i++)
     {
         s[i-1] = s[i];
     }
     s[n-1]=t;
 }
 void LeftString(char *s,int n,int m)//向左移动m 次
 {
     while(m--)
     {
         LeftShiftOne(s,n);
     }
 
 }

int _tmain(int argc, _TCHAR* sargv[])
{  
    char *s="I am a Student.";//字符串常量,不可通过指针修改char arr[]="I am a Student.";
    int n=strlen(s);
    cout<<s<<endl;
    cout<<n<<endl;
    ReverseString(s,0,5);
    cout<<s<<endl;
    LeftString(s,n,7);
    cout<<s<<endl;
    system("pause");
    return 0;
} 

以上代码运行到s[from]=s[to]会出现

projectOne.exe 中的 0x0086193f 处最可能的异常: 0xC0000005: 写入位置 0x00867838 时发生访问冲突
projectOne.exe 中的 0x0086193f 处有未经处理的异常: 0xC0000005: 写入位置 0x00867838 时发生访问冲突
 不知道原因

由于char *s="I am a student.";是一个字符串常量,是保存在static内存块里,不能通过指针修改

所以需要把它改成:char arr[]="I am a student.";

方法二:

先翻转每个单词,然后再翻转整个句子。如先将“I am a student.”反转为“I ma a .tneduts”,然后再对中间结果“I ma a .tneduts”整体翻转,即为 “student. a am I”。

#include <stdio.h>
#include <string.h>
//反转一个单词[from,to]区间内的字母
void reserveString(char arr[],int from, int to)
{
    while(from < to)
    {
        char tmp = arr[from];
        arr[from]= arr[to];
        arr[to] = tmp;
        from ++;
        to --;
    }

    
}
/*
//这样写也可以
 void reverseString(char arr[],int from,int to)
 {
	 for(int i=from;from<to;from++)
	 {
		 char tmp = arr[from];
		 arr[from] = arr[to];
		 arr[to] = tmp; 
		 to--;
	 }
 }
*/

//反转一句话,以'\0'结尾
void reserve(char ch[], int len)
{
    int i=0;
    int from = 0;
    int to   = 0;
    while(i<=len)//数组中每个字符都要判定,包括'\0'
    {
        if(ch[to] == ' ' || ch[to]=='\0')
        {
            reserveString(ch, from,to-1);   //先反转每个单词,[from,to-1]
            from = ++to;                    //寻找下一个单词。
        }
        else
        {
            to++;
        }
        i++;
    }
    reserveString(ch, 0,len-1);  //再整体反转
}

int main()
{
    char arr[]="I am a student.";
	int n=strlen(arr);
	cout<<arr<<n<<endl;
	reverseWord(arr,n);
	cout<<arr<<endl;
	reverseString(arr, 0, n-1);
	cout<<arr<<endl;
	system("pause");
	return 0;
}

 注意reverseString(arr, 0, n-1);//这边不能写成n,数组的下标比实际长度小1

 

猜你喜欢

转载自blog.csdn.net/usstmiracle/article/details/81453122
今日推荐