将字符串完全反转---大公司简单面试题

http://topic.csdn.net/u/20080711/14/00183de8-5fdf-4fac-a39c-c4dc343b0de5.html?seed=1292595069

 

 将字符串 String oldstr="I am  a  programmer"完全反转为"programmer  a  am I",最好不用函数,自己写,当然也可以用
这样的 题目很多人写不出,真是汗啊!我是用链表实现的,但是比较繁琐,算是过关了,今天特来寻求最好的解决方案

public class splitstr {
   
   
public static void main(String args[])
    {
    String oldstr
="I am a programmer";
    String[] str
= oldstr.split(" ");
    String finalstr
="";
   
for(int i=str.length-1;i>-1;i--)
    {
      finalstr
=finalstr+str[i]+" ";
    }
    System.out.println(finalstr);
    }
}

 

--------------------------------------------------------------------------------------------

 

String oldstr="I am  a  programmer";
      int i= oldstr.length();
      char[] tmp=new char[i];
      for(int k=0;k <i;k++){
          tmp[k]=oldstr.charAt(i-k-1);
      }
      oldstr=String.valueOf(tmp);
      System.out.println(oldstr);

 

--------------------------------------------------------------------------------------------

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class test
{

public static void main(String args[])
    {
    String a = "rosewj";
    StringBuffer sb = new StringBuffer();
   
    for(int i =  a.length()-1;i>=0;i-- ) {
    char c = a.charAt(i);
    sb.append(c);
   
    }
    System.out.println(sb);
    }

}

 

----------------------------------------------------------------------------------------------------

 

public class tts {
   
   
public static void main(String args[])
    {
    String oldstr
="I am  a   programmer";
    String[] str
= oldstr.split(" ");
    String finalstr
="";
   
for(int i=str.length-1;i>-1;i--)
    {   
     
if(str[i].equalsIgnoreCase(""))
      {
        
continue;
      }
     
if(i==0)
      {
          finalstr
=finalstr+str[i].trim();
         
continue;
      } 
      finalstr
=finalstr+str[i].trim()+" ";
    }
    System.out.println(finalstr);
    }
}

--------------------------------------------------------------------------------------------------

 

 String str = "i am  a   test";

    StringBuilder out
= new StringBuilder(str.length());
    StringBuilder field
= new StringBuilder();
   
   
char[] charArray = str.toCharArray();
   
   
for(int i = charArray.length - 1; i >= 0; i --) {
       
       
if(charArray[i] != ' '){
            field.insert(
0, charArray[i]);
           
        }
else {
           
if(field.length() != 0) {
                out.append(field.toString()) ;
                field
= new StringBuilder();
            }
            out.append(
" ");
        }
    }
   
   
if(field.length() != 0) out.append(field.toString());
    System.out.println(out.toString());

---------------------------------------------------------------------------------------------------------------

 

int i = 0;
String oldstr
=" I am  a   programmer";
int length = oldstr.length(); List<String> list = new ArrayList<String>();
//这是以空格开头的情况
if(oldstr.substring(0, 1).equals(" ")) {
    String space
= "";
   
int temp = 0;
   
for(int m = i; m < length; m++) {
       
if(oldstr.codePointAt(m) != 32) {
            temp
= m;
           
break;
        }
    }
    space
= oldstr.substring(i, temp);
    list.add(space);
    i
= temp;
}
while(i < length) {
   
//获取空格之间的单词
    int temp = 0;
    Boolean bool
= false;
    String word
= "";
   
for(int m = i; m < length; m++) {
       
if(oldstr.codePointAt(m) == 32) {
            temp
= m;
            bool
= true;
           
break;
        }
    }
   
if(!bool) {//说明是截取到oldstr的结尾
        temp = length;
    }
    word
= oldstr.substring(i, temp);
    list.add(word);
    i
= temp;
    bool
= false;
   
//获取单词之间的空格
    if(i < length) {
        String space
= "";
           
for(int m = i; m < length; m++) {
                    
if(oldstr.codePointAt(m) != 32) {
                temp
= m;
                bool
= true;
               
break;
            }
        }
       
if(!bool) {
            temp
= length;
        }
        space
= oldstr.substring(i, temp);
        list.add(space);
        i
= temp;
    }
}
String newstr
= "";
for(int j = list.size() - 1; j >= 0; j--) {
    newstr
+= list.get(j);
}
System.out.println(newstr);

--------------------------------------------------------------------------------------------------

 

public class StringTest {
private static String convert(String str) {
if (str == null) {
return null;
}

char[] cs = str.toCharArray();
char[] cs0 = new char[cs.length];
int temp = cs.length;

for (int start = 0; start < cs.length;) {
boolean isBlank = isBlank(cs[start]);
int end = start;
for (; end < cs.length; end++) {
if (isBlank != isBlank(cs[end])) {
break;
}
}
System.arraycopy(cs, start, cs0, temp - (end - start),
(end - start));
temp -= (end - start);
start = end;
}
return String.valueOf(cs0);
}

private static boolean isBlank(char c) {
return c == ' ';
}

public static void main(String[] args) {
System.out.println(convert("1"));
}
}

 

---------------------------------------------------------------------------------------------------

 

public class StringTest {
   
private static String convert(String str) {
       
if (str == null) {
           
return null;
        }

       
char[] cs = str.toCharArray();
       
char[] cs0 = new char[cs.length];
       
int temp = cs.length;
       
       
for (int start = 0; start < cs.length;) {
           
boolean isBlank = isBlank(cs[start]);
           
int end = start;
           
for (; end < cs.length; end++) {
               
if (isBlank != isBlank(cs[end])) {
                   
break;
                }
            }
            System.arraycopy(cs, start, cs0, temp
- (end - start),
                    (end
- start));
            temp
-= (end - start);
            start
= end;
        }
       
return String.valueOf(cs0);
    }

   
private static boolean isBlank(char c) {
       
return c == ' ';
    }

   
public static void main(String[] args) {
        System.out.println(convert(
"1"));
    }
}

-------------------------------------------------------------------------------------------------------

 

2个栈
先把整个字符串放进第1个栈
然后把第1个栈的字符一个个网外POP 同时PUSH进第2个栈 每遇到一个空格就是一个单词了
这时候把第2个栈的单词POP出来就行了,同时记得加个空格
这样依次把第1个栈内的字符处理完,楼主的要求打到了

-------------------------------------------------------------------------------------------------------

 

用正则表达式实现

Java code
   
   
String oldstr = " I am a programmer " ; List < String > list = new ArrayList < String > (); String regEx1 = " [a-zA-Z]+ " ; String regEx2 = " + " ; Pattern p1 = Pattern.compile(regEx1); Pattern p2 = Pattern.compile(regEx2); Matcher m = Pattern.compile( " ^ + " ).matcher(oldstr); if (m.find()) { list.add(m.group()); oldstr = m.replaceAll( "" ); } while (oldstr.length() > 0 ) { Matcher m1 = p1.matcher(oldstr); if (m1.find()) { list.add(m1.group()); oldstr = m1.replaceFirst( "" ); } Matcher m2 = p2.matcher(oldstr); if (oldstr.length() > 0 && m2.find()) { list.add(m2.group()); oldstr = m2.replaceFirst( "" ); } } String newstr = "" ; for ( int j = list.size() - 1 ; j >= 0 ; j -- ) { newstr += list.get(j); } System.out.println(newstr);


输出结果:
programmer  a  am I 这里有个空格

 

------------------------------------------------------------------------------------------------------------

 

import java.util.ArrayList;
import java.util.Arrays;

public class StringFZ {
public static void main(String[] args)
{
String oldstr="I am a programmer";
String[]new1 =oldstr.split(" ",0);

for(int i=new1.length-1;i>=0;i--)
{
System.out.print(new1[i]+" ");
}
}
}

 

-----------------------------------------------------------------------------------------------------

 

public class Test {

   
public static void main(String[] args) {
        String str
= "I am  a   programmer";
       
char[] chs = str.toCharArray();
       
for(int i = 0, offset = 0; i < chs.length; i++) {
           
char h = chs[chs.length - 1];
           
if(h == ' ') {
                offset
= i;
            }
           
for(int j = chs.length - 2; j >= offset; j--) {
                chs[j
+ 1] = chs[j];
            }
           
if(h == ' ') {
                chs[i]
= h;
                offset
++;
            }
else {
                chs[offset]
= h;
            }
        }
        System.out.println(chs);
    }
}

---------------------------------------------------------------------------------------------------------

 

public class convertString {
public static void main(String [] args){
char str = ' ';
String oldstr="I am  a  programmer";
int lenngth = oldstr.length();
StringBuffer newStr = new StringBuffer();
for(int i=0;i < lenngth ;i++){
str = oldstr.charAt(lenngth-1-i);
newStr.append(str);
}
System.out.println(newStr.toString());
}
}

 

-----------------------------------------------------------------------------------------------------------

 

public class splitstr {
   
    public static void main(String args[])
    {
    String oldstr="I am a programmer";
    String[] str = oldstr. [color=#0000FF]split(" ",-1);
  String finalstr="";
    for(int i=str.length-1;i>-1;i--)
    {
      finalstr=finalstr+str[i]+" ";
    }
    System.out.println(finalstr);
    }
}[/color]

 

------------------------------------------------------------------------------------------------------------

 

public class splitstr {
   
    public static void main(String args[])
    {
    String oldstr="I am a programmer";
    String[] str = oldstr.split(" ");
    String finalstr="";
    for(int i=str.length-1;i>-1;i--)
    {
      finalstr=finalstr+str[i]+" ";
    }
    System.out.println(finalstr);
    }
}

------------------------------------------------------------------------------------------------------------

 

public class splitstr {
   
    public static void main(String args[])
    {
    String oldstr="I am a programmer";
    String[] str = oldstr.split(" ",-1);
    String finalstr="";
    for(int i=str.length-1;i>-1;i--)
    {
      finalstr=finalstr+str[i]+" ";
    }
    System.out.println(finalstr);
    }
}

-------------------------------------------------------------------------------------------------------------

 

 

  
  
String oldstr = " I am a programmer " ; int index = oldstr.lastIndexOf( ' ' ); while (index >= 0 ) { System.out.print(oldstr.substring(index + 1 ) + ' ' ); oldstr = oldstr.substring( 0 ,index); index = oldstr.lastIndexOf( ' ' ); } System.out.println(oldstr);
  
  
 

----------------------------------------------------------------------------------------------------------------

 

import java.util.Iterator;
import java.util.Stack;

public class Test1 {
   
public static void main(String[] args) {
        String oldstr
="I am  a   programmer";
        Stack
<String> newStr = new Stack<String>();
        String temp
= "";
       
for (int i = 0; i < oldstr.length(); i++) {
           
if (i != oldstr.length() - 1 && oldstr.charAt(i) != ' ')
                temp
+= oldstr.charAt(i);
           
else {
                newStr.add(temp);
                temp
= "";
            }
        }
       
while(!newStr.empty())
            System.out.print(newStr.pop()
+ " ");
    }

}

 

------------------------------------------------------------------------------------------------------------

 

Java codepublic class splitstr {
       
public static void main(String[] args) {
        String s
= "i am  a   programmer";
        String regu
= "//s+";
        String regu1
= "//w+";
        String[] eg
= s.split(regu);
        String[] eg1
= s.split(regu1);
        String result
= "";
       
for(int i=eg.length-1;i>=0;i--){
            result
+= eg[i]+eg1[i];
        }
        System.out.println(result);
    }
}

---------------------------------------------------------------------------------------------------------------

 

   public static void main(String[] args) {
        String s
= "I am    a         Programmer";
       
int[] a = new int[100];
       
int i = 0, j = 1;
       
boolean flag = true;
        a[
0] = 0;
       
for(;i<s.length(); i++) {
           
if((s.charAt(i)==' ')==flag) {
                a[j
++] = i;
                flag
= !flag;

} } a[j--] = s.length();
        String result
= "";
       
while(j>=0) {
            result
+= s.substring(a[j], a[j+1]);
            j
--;
        }
        System.out.println(result);
    }

----------------------------------------------------------------------------------------------------------------

 

我好奇用c++写了一个 也是可以的。。

void changeDown(char const *str)
{
char strtemp[255];
int count=0,j=0;
while(str[j++])count++;
j=0;
for (int i=count-1;i>=0;i--)
{
if (str[i]!=' ')
{
if (i==0)
{
strtemp[j++]=str[i];
j--;
while (j!=-1)
{
cout < <strtemp[j--];
}
cout < <" ";
}
else
{
strtemp[j++]=str[i];
}
}
else//==' '
{
j--;
while (j!=-1)
{
cout < <strtemp[j--];
}
cout < <" ";
j=0;
}
}
}

 

---------------------------------------------------------------------------------------------------------------

 


public class text{

public static void main(String []args)
{
String A
="I am a programer";
String [] str
=A.split(" ");
for(int i=str.length-1;i>-1;i--)
{
  System.out.print(str[i]);
  System.out.print(
" ");
}
System.out.println();
}
}

--------------------------------------------------------------------------------------------------------------------

 

南开一百题里面的啊,比较简单的一个题目。


Java code
    
    
import java.util.Arrays; /** * 南开一百题 *对以空格或标点符号为分隔的所有单词进行倒排。 *最后处理的字符串(应不含标点符号)返回 *eg: You He Me-->Me He You * @author igogo007 * */ public class Nan003 { public static String strOL(String str) throws Exception{ StringBuffer buffer = new StringBuffer(str); int n = 0 ; // 数组长度 for ( int i = 0 ;i < buffer.length();i ++ ){ if ((buffer.charAt(i) < ' a ' || buffer.charAt(i) > ' z ' ) && (buffer.charAt(i) < ' A ' || buffer.charAt(i) > ' Z ' )){ n ++ ; } } // 定义数组 StringBuffer[] array = new StringBuffer[n + 1 ]; // 初始化数组 for ( int t = 0 ;t < n + 1 ;t ++ ){ array[t] = new StringBuffer( "" ); } // 依次存入数组 for ( int j = 0 ,x = n;j < buffer.length();j ++ ){ if ((buffer.charAt(j) < ' a ' || buffer.charAt(j) > ' z ' ) && (buffer.charAt(j) < ' A ' || buffer.charAt(j) > ' Z ' )){ x -- ; } else { array[x].append(buffer.charAt(j)); } } return Arrays.toString(array); } public static void main(String[] args) { try { System.out.println(strOL( " You He Me " )); System.out.println(strOL( " My name is abc.A BC,def is fdc " )); } catch (Exception e){ System.out.println( " 错误: " + e.getMessage()); } } }

 

---------------------------------------------------------------------------------------------------------------------------------

 

我用堆栈写了一个

Java code
    
    
package dd; class string{ public static void main(String[] args){ String str = " I am a programer " ; String newstr = "" ; stack s = new stack( 50 ); for ( int i = 0 ;i < str.length();i ++ ){ if (str.charAt(i) == ' ' ){ if (newstr != "" ){ s.push(newstr); } s.push( " " ); newstr = "" ; } else { newstr += str.charAt(i); if (i == str.length() - 1 ){ s.push(newstr); } } } System.out.println( " 输出结果为: " ); s.pop(); } } class stack { private String items[]; int flag =- 1 ; stack( int size){ items = new String[size]; } void push(String data){ if (flag < items.length){ items[ ++ flag] = data; } else { System.out.println( " 堆栈溢出! " ); } } void pop(){ String output = "" ; while (flag >- 1 ){ output += items[flag -- ]; } System.out.println(output); } }
-------------------------------------------------------------------------

import java.util.*;

public class UsingStackReverseString {
    public static void main (String args[]){
        String str1 = "  I am  a   programmer  ";
        String str2 = "";
    
        Stack stack1 = new Stack();
        Stack stack2 = new Stack();
        
        char[] strArray = str1.toCharArray();
        
        for (int i=0; i<strArray.length; i++){
            stack1.push(strArray[i]);
        }
        
        while (!stack1.empty()){
            if (stack1.peek() == (Object)' '){
                
                while (!stack2.empty()){
                    str2 += stack2.pop();
                }
                
                str2 += stack1.pop();
            }
            else{
                stack2.push(stack1.pop());
            }
            
            while (!stack2.empty()){
                str2 += stack2.pop();
            }
        }
        
        System.out.print(str2);
        
    }
}


Java code
     
     
remmargorp a ma I

用栈实现的...无论多少个空格都可以...
-------------------------------------------------------------------------
我给出一个代码,大家参考 
Java code
     
     
public static void reverse() { String s = " i am a programmer " ; // 几个空格的数量分别为1,2,3,4个 String[] eg = s.split( " " , - 1 ); String result = "" ; for ( int i = eg.length - 1 ; i > 0 ; i -- ) { result += eg[i] + " " ; } result += eg[ 0 ]; // 这里要注意第一个字符的前面是不能增加空格的。否则就多了一个空格 System.out.println(result); }

此代码收录于:http://www.java2000.net/p7786
-------------------------------------------------------------------------------
  
  
   
   C/C++ code 
  
  
  
  
    
    
#include < iostream > #define maxn 5 using namespace std; string str[maxn]; string space[] = { " " , " " , " " , " " , " " }; const int n = 4 ; int main(){ for ( int i = 1 ;i <= n;i ++ ) cin >> str[i]; for ( int i = n;i >= 1 ;i -- ) cout << str[i] << space[i]; return 0 ; }
-------------------------------------------------------------------------------
C/C++ code
    
    
/* Name: String Reverse Copyright: 0.99 Author: busycai Date: 31-07-08 20:10 Description: Stack Simulation(without any stardard function call). */ /* 字符串反转 输入:I am a Programmer 输出:Programmer a am I 算法:堆栈模拟 */ #include < iostream > using namespace std; void Reverse( char * str){ char stack[ 100 ]; int stkTop = - 1 , i, idx = 0 ; while (str[idx] != ' /0 ' ) idx ++ ; idx -- ; while (idx >= 0 ){ if (str[idx] != ' ' ) stack[ ++ stkTop] = str[idx]; else { for (i = stkTop; i >= 0 ; i -- ) cout << stack[i]; stkTop = - 1 ; cout << ' ' ; } idx -- ; } if (stkTop >= 0 ){ while (stkTop >= 0 ) cout << stack[stkTop -- ]; } cout << endl; } int main() { char str[ 255 ]; while (gets(str)){ Reverse(str); } return 0 ; }
---------------------------------------------------------------------
 
 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值