Chapter 1 Arrays and Strings - 1.2

Problem:

1.2 Write code to reverse a C-Style String. (C-String means that "abcd" is represented as five characters, including the null character.)

This one is quite easy:

# -*- coding:utf-8 -*-
import string
# There is no NULL at the end of a string in Python,
# so we use blank space '' as indicator of end
def reverseCStyleStr(str):
    length = len(str) - 1
    # One cannot change a string,
    # so we copy it as a sequence
    strSeq = [i for i in str]
    for i in range(0, (length+1)//2):
        strSeq[i], strSeq[length-1-i] = strSeq[length-1-i], strSeq[i]
    return string.join(strSeq)

if __name__ == '__main__':
    #str = '12345 '
    str = '1234 '
    print reverseCStyleStr(str)

Note that the first line of above code gives the program the ability to deal with wide characters.

As the standard answer says, the only "gotcha" is to try to do it in place and be careful for the null character.

One thing to mention is that, I was so stupid that I came up with a "big improvement": split the string evenly, then swap the two segments. Although this solution runs in O(1), it is totally wrong because it doesn't reverse the string...

I even tried to implement it as:

#include <cstring>
#include <cstdio>

void reverseCStyleStr(char* pStr)
{
	int nStrLen = strlen(pStr);

	// Calculate the head of right part
	int nOffset = 0;
	if (nStrLen%2 == 0)
	{
		nOffset = nStrLen/2;
	}
	else
	{
		nOffset = nStrLen/2 + 1;
	}
	char* pRightHead = pStr + nOffset;

	// Memory for swaping
	char* pTmp = new char[nStrLen/2];

	// Swap left part and right part
	memcpy(pTmp, pStr, nStrLen/2);
	memcpy(pStr, pRightHead, nStrLen/2);
	memcpy(pRightHead, pTmp, nStrLen/2);

	delete[] pTmp;
}
int main()
{
	char* pStr = new char[6];
	memcpy(pStr, "12345", 6);
	// DO NOT USE: char* pStr = "12345";
	reverseCStyleStr(pStr);
	printf("%s", pStr);
	getchar();
	delete[] pStr;
	return 0;
}

Although it's a wrong solution, it taught me something about literal strings. Note that the commented line in main function is wrong. You can never change a literal string, because it's in the const pool. Thus, when I firstly used this line, I got a exception about illegal memory access when I wanted to swap the two parts of a string.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值